﻿/**
TODO: SessionID or RoomID
Pass the session id to server..
**/
/* Update Broh*/
define([
    "jQuery",
	"jQuery-ui",
    "drag",
	"app/views/draw",
	"app/menu/menu-toolbox",
	"app/menu/menu-recover",
	"app/menu/menu-uplimg",
	"app/menu/menu-uplfile",
	"app/menu/menu-page",
	"app/menu/menu-page-file",
	"app/menu/menu-save-as-file",
	"app/menu/menu-chart-toolbox",
	"app/menu/menu-initial-table-toolbox",
	"app/menu/menu-pick-color-toolbox",
	// "app/menu/menu-text-logo-toolbox", 
	"app/menu/menu-property-toolbox", 
	"app/menu/menu-open-file-toolbox", 
	"app/menu/menu-open-file-template-toolbox", 	
	"app/menu/menu-lock-object-toolbox", 
	"app/menu/menu-unlock-object-toolbox", 
	"app/menu/menu-list-user",
	"app/kinetic/kinetic-main",
	"app/kinetic/kinetic-edit",
	"app/app-util",
	"kineticJs",
	"app/menu/stamp-toolbox",
	"iframeTransport",
	"app/menu/nicEdit",
	"app/text/text-main",
	"app/text/sticky-text-main",
	"rightClick",
	// "touchPunch",
	"colorPicker",
	"dragableTouch",
	"colorPicker",
	"html2Canvas",
	"canvas2Image",
	"chatbox",
	"base64Img",
	"gridBuilder",
	"printArea",
	"touchPan",
	"app/menu/bubble-toolbox",
	"app/menu/sticky-toolbox"
	], function (
    $,
	$ui,
    drag,
	drawerView,
	toolbox,
	recoverMenu,
	upload,
	uploadFile,
	newPage,
	pageFile,
	saveAsFile,
	chartToolbox,
	initialTableToolbox,
	pickColorToolbox,
	// textLogoToolbox,
	propertyToolbox,
	openFileToolbox,
	openFileTemplateToolbox,
	lockObjectToolbox,
	unlockObjectToolbox,
	listUserMenu,
	kineticMain,
	kineticEdit,
	util,
	kineticJs,
	stampToolbox,
	iframeTransport,
	nicEdit,
	richText,
	stickyText,
	rightClick,
	// touchPunch,
	colorPicker,
	dragableTouch,
	colorPicker,
	html2Canvas,
	canvas2Image,
	chatbox,
	base64Img,
	gridBuilder,
	printArea,
	touchPan,
	bubbleToolbox ,
	stickyToolbox 
	) {
	
    return {
		test : false, //Firman : Pan Function
		lastClickPointTools:{x:0,y:0},
		lastClickPoint:{x:0,y:0},
		lastClickGlobalPoint:{x:0,y:0},
		positionChange:{left:0,top:0},
		sizeChange:{width:0,height:0},
		editProp : {x :0,y:0,width:0,height:0,bgCanvas:""},
		positionAlign:{left:0,top:0},
		fileId: "fileId",
		kinetic: kineticMain,
		kineticEdit : kineticEdit,
		Util : util,
		recoverMenu : recoverMenu,
		toolbox : toolbox,
		richText : richText,
		stickyText : stickyText,
		upload : upload,
		uploadFile : uploadFile,
		newPage : newPage,
		pageFile : pageFile,
		saveAsFile : saveAsFile,
		chartToolbox : chartToolbox,
		initialTableToolbox : initialTableToolbox,
		pickColorToolbox : pickColorToolbox,
		// textLogoToolbox : textLogoToolbox,
		propertyToolbox : propertyToolbox,
		openFileToolbox : openFileToolbox,
		openFileTemplateToolbox : openFileTemplateToolbox,
		lockObjectToolbox : lockObjectToolbox,
		unlockObjectToolbox : unlockObjectToolbox,
		listUserMenu : listUserMenu,
		draw: drawerView,
		rootCanvas : 'rootContainer',
		kineticCanvas: 'kineticCanvas',
		stampToolbox : stampToolbox,
		bubbleToolbox : bubbleToolbox,
		stickyToolbox : stickyToolbox,
		kineticExporterCanvas : 'kineticExporterCanvas',
		dragMode: true,
		activeObject : false,
		isDrag:false,
		lastUpdateTime:0,
		prepareCreation:false,
		creationMode:false,
		creationKind: false,//'shape',//shape,text,stamp
		creationType:'pencil',
		creationStartPoint: {x:0,y:0},
		creationObject: null,
		openedTool: false,
		option : false,
		optionTemplate : false,
		heightChartDraw : 0,
		widthChartDraw : 0,
		listFileLayersCount : 0,
		tempPageId : false, 
		openWindowPreview : 1,
		chatbox:chatbox,
		initialWidth : 0,
		chatboxContainer:null,
		isUpdate : 0,
		lastZ : 20,
		idIndicatorLast : 0,
		idPageSelcLast : 1,
		isModeArea : 0,
		justSelectAnObject : false,
		pageCount : 0,
		isRecover : false,
		pages : new Array(),
		lockDataObject:0,
		statusLock:0,
		currIdData:0,
		isSurface:false, //Firman Notes - Surface : Handler For Surface
		lockObjectImg:0,
		arrayLockObj:{},
		lockedObjectList:{lockedObject:[]},
		withoutPass:0,
		passVal:null,
		objlck: 0,
		widthMinTable : 0,
		heightMinTable : 0,
		canvasWidth : 0,
		canvasHeight : 0,
		optionImage : false,
		actionStack : [],
		updatingThumbnail :false,
		currentStackIndex : -1,
		onDrag : false,
		baseUrl:document.getElementById("base_url").value,
		fileId:document.getElementById("file_id").value,
		pageId:document.getElementById("page_id").value,
		username:document.getElementById("u_name").value,
		userId:document.getElementById("u_id").value,
		nodeURL:document.getElementById("node_url").value,
		filename : document.getElementById("file_name").value,
		groupname : document.getElementById("group_name").value,
		activeObjectReserve : false,
		shortFilename : document.getElementById("file_name").value,
		isTeacher : document.getElementById("is_teacher").value,
		onlineCheckInterval : false,
		socket : {
			on : function(data,test){},
			emit : function(data,test){}
		},
		lockEnum:{
			MOVEMENT:1,
			EDIT:2,
			ALL:3,
			NOT_LOCKED:3,
			SELECT:4,
		},
		onlineUserData:[],
		pan : function(){
			
		},

        init: function () {
			var locale=$("#app_lang").val();
			if(locale == "english")
			{
				String.locale = "en";
			}
			else if(locale == "japanese")
			{
				String.locale = "jp";
			}
			var truncFileName=App.filename;
			if(truncFileName.length > 17)
			{
				truncFileName=truncFileName.substring(0,17);
				truncFileName+="...";
			}
			App.shortFilename=truncFileName;
			
			initialWidth = $(window).width();
			// window.onbeforeunload = function() {
// alert('unl');			
			// App.socket.emit('cm_quit', {
												// username:App.username,
												// userId:App.userId,
												// roomId:App.fileId, 
											// });
			// };
			
			App.socket=io.connect(App.nodeURL,{"sync disconnect on unload":true});
			App.socket.on('connected', function(data){
			});
			var inFormOrLink;
			$('a').live('click', function() { inFormOrLink = true; });
			$('form').bind('submit', function() { inFormOrLink = true; });
		
			
			var liveTimeout, confTimeout, sessionTimeout;
			// liveTimeout = setTimeout(function(){
										// var url = App.baseUrl+"CommHub/delete_session"; 
										// var request=$.ajax({
											// type: 'POST',
											// url: url 
										// });
										// request.done(function(msg) {
											// App.socket.emit('cm_update_user_data', {
												// username:App.username,
												// user_id:App.userId,
												// roomid:App.fileId, 
											// });
											// alert("Session has Expired !");
											// setTimeout(function(){
												// window.location.href = App.baseUrl;
											// }, 2000);
										// });
									// }, 1000*3600*24);
			App.onlineCheckInterval = setInterval(function(){
					var url = App.baseUrl+"CommHub/online_check"; 
						var request=$.ajax({
							type: 'POST',
							url: url 
						});
						request.done(function(msg) {
							if(!msg){
								clearInterval(App.onlineCheckInterval);
								if(App.activeObject)
								{				
									App.socket.emit('cm_unlock', {roomid: App.fileId,pageid:App.pageId, objectId: App.activeObject.attr("id"), id: App.userId,type:"object", status:0, userName: App.username, dateCreate: App.activeObject.attr("created_date")});
									
								} 
								App.socket.emit('cm_update_user_data', {
										username:App.username,
										user_id:App.userId,
										roomid:App.fileId, 
								});
								$("#overlay").show();
								// Nanda - Notes: When back to home (old=timeout 10s, new=timeout 3s)
								// alert("Session has Expired !");
								setTimeout(function(){
										$("#overlay").hide();
										window.location = App.baseUrl+"home/";
								}, 1000);
								
							}
						});
			},5000);
			$(document).bind('click', function()
			{ 
			  clearTimeout(liveTimeout); 
			  liveTimeout = setTimeout(function(){
										var url = App.baseUrl+"CommHub/delete_session"; 
										var request=$.ajax({
											type: 'POST',
											url: url 
										});
										request.done(function(msg) {
											App.socket.emit('cm_update_user_data', {
												username:App.username,
												user_id:App.userId,
												roomid:App.fileId, 
											});
											setTimeout(function(){
												window.location.href = App.baseUrl;
											}, 2000);
											// window.location.href = App.baseUrl;
										});
									}, 1000*3600*24);
									
			});  
			App.socket.on('sm_auth', function(data){
				$("#overlay-event").hide();
				App.socket.emit('cm_transfer_lock', {roomid: App.fileId,pageid:App.pageId});	 
					
				App.chatboxContainer = $("#chat_div").chatbox({id:App.username, 
                                                user:{key : "value"},
                                                title : "Chat Box",
												hidden : true,
                                                messageSent : function(id, user, msg) {
                                              	 	 var cObj = {username:App.username,message:msg};
                                              	 	 var url = App.baseUrl+"CommHub/add_chat_history";
													 var data = {"last_update_time": App.lastUpdateTime,
														"file_id":  App.fileId,
														"user_id":  App.userId,
														"username":  App.username,
														"message": msg
														};
													 var request=$.ajax({
														type: 'POST',
														url: url,
														data:data
													 });	
                                                	 App.socket.emit('cm_chat', {roomid: App.fileId, objects:cObj, id: App.userId}); 
													 $("#chat_div").chatbox("option", "boxManager").addMsg(id, msg,true);
                                                }});
				
				App.lockedObjectList=data.lockedInThisPage; 
				App.applyLock(data.lockedInThisPage);
				console.log(data.users);
				console.log(data.roomid);
				for(var i=0;i<data.users.length;i++)
				{
					console.log(data.users[i]);
					if(data.users[i].room == App.fileId)
					{
						App.onlineUserData.push(data.users[i]);
					}
				}
				App.listUserMenu.populate(App.onlineUserData);
				
				App.loadChatHistory();
			});
			App.socket.on('sm_update_user_data', function(data){
				if(data.roomid == App.fileId){
					App.onlineUserData=[];
					for(var i=0;i<data.users.length;i++)
					{
						console.log(data.users[i]);
						if(data.users[i].room == App.fileId)
						{
							App.onlineUserData.push(data.users[i]);
						}
					}
					App.listUserMenu.populate(App.onlineUserData);
				}
			});
			App.socket.on('sm_quit', function(data){
				if(data.roomid == App.fileId){
					// alert("sm_quit "+data.username);
				}
			});
			App.socket.on('sm_chat', function(data){
				if(data.roomid != App.fileId)
					return
				 $("#chat_div").chatbox("option", "boxManager").addMsg(data.object.username, data.object.message,false);
			});
			App.socket.on('sm_user_dc', function(data){
					console.log('sm_user_dc '+data.removed.username);
					if(data.roomid == App.fileId)
					{
						App.onlineUserData=[];
						for(var i=0;i<data.users.length;i++)
						{
							if(data.users[i].room == App.fileId)
							{
								App.onlineUserData.push(data.users[i]);
							}
						}
						App.listUserMenu.populate(App.onlineUserData);
					}
			});
			App.socket.on('sm_new', function(data){  
				if(data.roomid != App.fileId)
				{
					return;
				}
				
				if(data.pageid == App.pageId){
					if(data.type=="image")
					{
						App.loadDrawingObject(data.object);
					}
					else if(data.type=="text")
					{
						App.loadTextObject(data.object);
					}
					else if(data.type=="buble")
					{
						App.loadTextObject(data.object);
					}
					else if(data.type=="sticky-text")
					{
						App.loadTextObject(data.object);
						// App.loadStickyTextObject(data.object);
					}
					else if(data.type=="chart")
					{	
						App.loadChartObject(data.object);
					}
					else if(data.type=="attach")
					{	
						App.loadDrawingObject(data.object);
					}
					else if(data.type=="table")
					{	 
						App.loadTableObject(data.object);
					}
					
				}
			});
			App.socket.on('sm_delete', function(data){
				//console.log("sm_delete");
				if(data.roomid != App.fileId)
					return
				var existingObject=false;
				if(data.type=="file")
				{
					if(data.deletedId == App.fileId){ 
						alert(App.localize("%workspace_deleted_dialog"));
						window.location.replace(App.baseUrl+"home");
					}	
				}
				else if(data.type=="object")
				{
					$('#rootContainer').children().each(function(){
						if($(this).attr('id') == data.deletedId)
						{
							existingObject=$(this);
						}
					});
					if(existingObject)
					{
						if(existingObject==App.activeObject)
						{
							App.activeObject=false;
						}
						existingObject.remove();
					}
				}

			});
			
			//Broadcast dari server, ada yang melakukan delete page
			App.socket.on('sm_delete_page', function(data){
				App.updatingThumbnail=true;
				if(data.roomId == App.fileId)
				{
				
						var index =-1;
						//Identifikasi Page yang di delete
						for(var i =0;i<App.pages.length;i++)
						{
							if(App.pages[i].attr('page-id') == data.pageId)
							{
								index = i;
								break;
							}
						}
						
						//Remove Page Element dari front end
						App.pages.splice(index, 1);
						$('.layerboxContainer').children().each(function(e){
							if($(this).attr('page-id') == data.pageId)
							{
								$(this).remove();
							}
						});
						console.log(data.newArrangement);
						
						
						//Update Id Pada Page
						for(var i =0;i<data.newArrangement.length;i++)
						{
							if(i >= index)
							{
								var prevPageId = App.pages[i].attr('page-id');
								App.pages[i].attr('page-id',data.newArrangement[i]);
								App.pages[i].find().attr('src', App.baseUrl+"documents/"+App.fileId+"/thumb-"+App.pages[i].attr('page-id')+".png?ts="+(new Date).getTime());
							}
						}
						
						//Cek apakah user sedang ada pada page yang didelete
						if(data.pageId == App.pageId)
						{
							alert(App.localize("%page_deleted_by_other"));
							App.pages[0].trigger('click');
							App.pageId=App.pages[0].attr('page-id');
						}	
						
						App.pageCount--;
						App.updateFileTitle();
				}
				
				App.updatingThumbnail=false;
			});
			App.socket.on('sm_new_page', function(data){
				if(data.roomid != App.fileId)
					return
				App.loadPageObject(data.object);
				console.log("Page Added Successfully");
				App.pageCount++;
				App.updateFileTitle();
			
			});
			App.socket.on('sm_object_send',function(data){
				//console.log("RECEIVE OBJECT FROM JNE");
				//console.log(data);
				if(data.kind == "text"){
					if(data.cmd == "content-update"){
						$("#text_content_"+data.id).html(data.object.content_object);
						$("#"+data.id).css('width', data.width);
						$("#"+data.id).css('height', data.height);
						$(".resize-grip"+data.id).hide();
					}
				}
				if(data.kind == "sticky-text"){
					if(data.cmd == "content-update"){
						$("#"+data.id).css('background-color', data.object.bg_color);
						$("#"+data.id).css('width', data.width);
						$("#"+data.id).css('height', data.height);
						$("#text_content_"+data.id).html(data.object.content_object);
						$(".resize-grip"+data.id).hide();
						
					}
				}
				App.toggleMobileMenuVisibility(data.id,false);
			});
			App.socket.on('sm_update', function(data){
				if(data.roomid != App.fileId)
					return
				var existingObject=false;	//check if it's an existing object
				$('#rootContainer').children().each(function(){
					if($(this).attr('id') == data.objId)
					{
						existingObject=$(this);
					}
				});
				if(existingObject)
				{
					if(data.coordinate.top != -1)
					{
						existingObject.css('top',(data.coordinate.top));
						existingObject.css('left',(data.coordinate.left));
					}
					
					if(data.size.width != -1)
					{
						existingObject.css('width',(data.size.width));
						existingObject.css('height',(data.size.height));
					}

					
				}
			});
			App.socket.on('sm_update_image', function(data){
				if(data.roomid != App.fileId)
					return
				var existingObject=$("#"+data.objId);	//check if it's an existing object
				
				if(existingObject)
				{
					$("#img"+data.objId).attr('src',App.baseUrl+data.image_url);		
				}
			});
			App.socket.on('sm_update_single_object', function(data){
				if(data.roomid != App.fileId)
					return;
					
				console.log(data);
				var existingObject=$("#"+data.id);	//check if it's an existing object
				console.log(existingObject);
				if(existingObject)
				{
					var existingType=existingObject.attr('object_type');
					//update content
					var newContent = false;
					if(existingType == "text" || existingType == "buble" || existingType == "sticky-text")
					{
						if($("#text_content_"+data.id).html() != data.content)
						{
							$("#text_content_"+data.id).html(data.content);
						}
						if(existingType == "sticky-text")
						{
							if(existingObject.css('background-color') != data.background)
							{
								existingObject.css('background-color', data.background);
							}
						}
					}
					else if(existingType == "image")
					{
						if($("#img"+data.id).attr('src') != data.content)
						{
							$("#img"+data.id).attr('src',App.baseUrl+data.content);
						}
					}
					else if(existingType == "table")
					{
						if($("#tbl_"+data.id).html() != data.content)
						{
							$("#tbl_"+data.id).html(data.content);
						}
					}
					else if(existingType == "chart")
					{
						var chartObj = $("#"+data.id);
						if(chartObj)
						{
							chartObj.attr('type',data.content.type)
							.attr('object_type',data.content.object_type)
							.attr('chart-data',data.content.data_chart)
							.attr('type_chart',data.content.type_chart)
							.attr('color1',data.content.color1)
							.attr('color2',data.content.color2)
							.attr('color3',data.content.color3);
							 $("#img"+data.id).attr('src',App.baseUrl+data.content.image_url);
						}
					}
					
					
					if(data.posx != -1 && data.posy != -1 )
					{
						existingObject.css('left',parseInt(data.posx)+"px");
						existingObject.css('top',parseInt(data.posy)+"px");
					}
					
					if(data.width != -1&& data.height != -1 )
					{
						existingObject.css('width',parseInt(data.width)+"px");
						existingObject.css('height',parseInt(data.height)+"px");
					}
				}
				
			});
			App.socket.on('sm_lock', function(data){
				if(data.roomid != App.fileId)
					return
				if(App.fileId == data.roomid)
				{ 
					App.lockedObjectList=data.lockedInThisPage; 
					App.applyLock(data.lockedInThisPage);
				}
				
			});
			App.socket.on('sm_deselect_object', function(data){
				if(App.pageId == data.pageId && App.fileId == data.roomId)
				{
					if(App.richText.menu.isShow && ($("#"+data.objectId).attr('object_type') == "buble" || $("#"+data.objectId).attr('object_type') == "text" || $("#"+data.objectId).attr('object_type') == "sticky-text"  ) && data.objectId == App.richText.menu.id){
							return;
					}
					$("#"+data.objectId+"-c").html('');
					$("#"+data.objectId+"-c").hide();
				}
			});
			App.socket.on('sm_select_object', function(data){
				if(App.pageId == data.pageId && App.fileId == data.roomId)
				{
					if(App.richText.menu.isShow && ($("#"+data.objectId).attr('object_type') == "buble" || $("#"+data.objectId).attr('object_type') == "text" || $("#"+data.objectId).attr('object_type') == "sticky-text"  ) && data.objectId == App.richText.menu.id){
							return;
					}
					$(".user_note").each(function(index){
						var cu = $(this).attr("current_user");
						if(cu != "-1" && cu == data.username && $(this).attr('id') != data.objectId+"-c")
						{
							$(this).attr("current_user","-1");
							$(this).html('');
							$(this).hide();
						}
					});
					$("#"+data.objectId+"-c").html('');
					$("#"+data.objectId+"-c").attr('current_user',data.username);
					
					var fontStr = $('<font></font>').attr({'size':'2', 'face':'comic sans ms'}).appendTo($("#"+data.objectId+"-c")); 
					// if(data.userId.length > 7 ){
						// var strCreated =  data.userId.substring(0,7) + "...<br>";
					// }else{
						// var strCreated =  data.userId + "<br>";
					// }
					if(data.username.length > 7 ){
						var strCreated =  data.username.substring(0,7) + "...<br>";
					}else{
						var strCreated =  data.username + "<br>";
					}
					fontStr.append(strCreated);
					$("#"+data.objectId+"-c").show();
				}
			});
			
			App.socket.on('sm_unlock', function(data){
			//console.log("sm_unlock");
				//console.log(data);
				if(App.fileId == data.roomid)
				{
					if(App.pageId == data.pageid)
					{
						//console.log(data);
						App.lockedObjectList=data.lockedInThisPage;
						if(App.richText.menu.isShow && ($("#"+data.objectid).attr('object_type') == "buble" || $("#"+data.objectid).attr('object_type') == "text" || $("#"+data.objectid).attr('object_type') == "sticky-text"  ) && App.richText.menu.id == data.objectid ){
								return;
						}
						App.activateLockedObject(data.objectid);
					}
				}
			});
			
			App.socket.on('sm_select_active_object', function(data){
			//console.log("sm_select_active_object");
				if(App.fileId == data.roomid)
				{
					if(App.pageId == data.pageid)
					{
						//console.log(data);
						App.lockedObjectList=data.lockedInThisPage;
						
						App.activateLockedObject(data.objectid);
					}
				}
			});
		
			
			App.socket.on('sm_z_index', function(data){
				// //console.log('njnjfjsafaks');
				//console.log("id "+ data.objectId + "z_index : "+data.z_index);
				if(App.fileId == data.roomid)
				{
					if(App.pageId == data.page)
					{
						$("#"+data.objectId).css('z-index',data.z_index); 
						if(data.z_index <=10)
							$("#"+data.objectId).attr('back-layer','1');
						else if(data.z_index > 20)
							$("#"+data.objectId).removeAttr('back-layer');		
					}
				}
			});
			
			App.socket.on('sm_background', function(data){ 
				$('#rootContainer').css('background-image', 'url(' + App.baseUrl+'documents/'+App.fileId+'/background-'+ App.pageId +'.png?ts='+(new Date).getTime()+' )');
				$('#rootContainer').css('background-size', '100%');
				
				App.propertyToolbox.heightGrid=0;
				App.propertyToolbox.isGrid=0;
				App.propertyToolbox.isDashed=0;
			 
			});
			stampToolbox.init();
			kineticMain.init();
			drawerView.init();
			toolbox.init();
			richText.init();
			stickyText.init();
			upload.init();
			uploadFile.init();
			newPage.init();
			pageFile.init();
			saveAsFile.init();
			chartToolbox.init();
			initialTableToolbox.init();
			pickColorToolbox.init();
			// textLogoToolbox.init();
			propertyToolbox.init();
			openFileToolbox.init();
			openFileTemplateToolbox.init();
			recoverMenu.init();
			lockObjectToolbox.init();
			unlockObjectToolbox.init();
			listUserMenu.init();
			bubbleToolbox.init();
			stickyToolbox.init();
			
			//First : Generate Thumbnail
			App.htmlToImage(App.pageId);
			// var intval = setInterval("App.htmlToImage(App.pageId)", 5000);
			var intval = setInterval(function(){
					//perodically refresh thumbnail
					for(var i =0;i<App.pages.length;i++)
					{
						var timeStamped = App.baseUrl+"documents/"+App.fileId+"/thumb-"+App.pages[i].attr('page-id')+".png?ts="+(new Date).getTime();
						var imageElement = App.pages[i].children();
						imageElement.attr('src',timeStamped)
									.attr('width',"80px")
									.attr('height',"60px");
					}
			}, 5000);
			 
			document.getElementById(App.kineticCanvas).style.display = "none";
			document.getElementById(App.kineticExporterCanvas).style.display = "none";
			
			$('#rootContainer').on('click',function(event){
				var zoom = initialWidth/$(window).width();
				
				App.lastClickPointTools.x = event.pageX;
				App.lastClickPointTools.y = event.pageY;
				var offset = $(this).offset();
				var posX = (event.pageX - offset.left)/zoom ,posY = (event.pageY - offset.top)/zoom;
				App.lastClickGlobalPoint.x = event.pageX/zoom;
				App.lastClickGlobalPoint.y = event.pageY/zoom;
				App.lastClickPoint.x = (event.pageX - offset.left)/zoom;// - event.target.offsetLeft;
				App.lastClickPoint.y = (event.pageY - offset.top)/zoom;// - event.target.offsetLeft;
				 if(App.creationMode)
				 {
					if(App.creationKind=="stamp")
					{
						App.addStamp(App.creationType,posX,posY);
					}
					
					
				 }
				 if(App.dragMode){
					App.isDrag = false;
				}
			
				if(App.activeObject && !App.justSelectAnObject && !App.openedTool)
				{				
					var oldActiveWidth = App.activeObject.width();
					var oldActiveHeight = App.activeObject.height();
					App.activeObject.css('border','0px dashed #000000');
					
					if(!App.inBackLayer(App.activeObject))
					App.activeObject.css('z-index','18'); 
					
					$(".resize-grip"+App.activeObject.attr("id")).hide();
					App.toggleMobileMenuVisibility(App.activeObject.attr('id'),false);
					
					App.activeObject.width(oldActiveWidth);
					App.activeObject.height(oldActiveHeight);
					App.socket.emit('cm_deselect_object', {
									roomId: App.fileId, 
									pageId: App.pageId, 
									userId: App.userId,
									username: App.username,
									objectId:App.activeObject.attr('id') 
					});
					App.socket.emit('cm_unlock', {
							roomid: App.fileId,
							pageid:App.pageId,
							status:App.lockEnum.SELECT,
							objectId: App.activeObject.attr('id'), 
							id: App.userId,
							password:"", 
							without_pass:App.withoutPass
						});
					App.activeObject=false;
				} 
				if(App.justSelectAnObject)
				{
					App.justSelectAnObject=false;
				}
			});
			
			
			
			option = { width: 150, items: [
				   
						{  	text: App.localize("%context_edit"), 
							alias: "edit", 
							action: function(){
										App.editObject();
									} 
						},
						{ 	text: App.localize("%context_delete"),  
							alias: "delete", 
							action: function(){
										App.deleteObject();
									} 
						},
						{  	text: App.localize("%context_copy"),  
							alias: "copy", 
							action: function(){
										App.copyObject();
									} 
						},
						{  	text: App.localize("%context_background"),  
							alias: "setback",
							action: function(){
										App.setImageAsBackground();
									} 
						},
						{ 	type: "splitLine" },
							{  	text: App.localize("%download_attachment"),  
							alias: "dl_attach",
							action: function(){
										if(App.activeObject)
										{
											if(App.activeObject.attr("object_type") == "attach")
											{
												window.open(App.baseUrl+App.activeObject.attr("content_file"), 'Download');
											}
											else
											{
												alert(App.localize("%only_attachment_warning"));
											}
										}
									} 
						},
						
						{ 	type: "splitLine" },
						{ text: App.localize("%context_lock"),
							alias: "lock-1", type: "group", width: 170, items: [
							{ 	text: App.localize("%lock_object"),  
								 alias: "2notTouch", 
								action: function(){
										var r=confirm(App.localize("%lock_obj_confirmation"));
										if (r==true)
										{
											App.lockObject("2notTouch");
										}
								} 
							}, 
							{ 	text:  App.localize("%context_unlock"),  
								
								alias: "unlock", 
								action: function(){
											App.unlockObject();
										}
							} 
						]
						},
						{ 	text: App.localize("%locked_object_desc"),  
							alias: "lock_desc", 
							action: function(){
										
									} 
						},
						{ text: App.localize("%context_aligment"), icon: "", alias: "alignment-1", type: "group", width: 300, items: [
							{ 	text: App.localize("%context_aligment_horizontal"),  
								 
								alias: "horizontal", 
								action: function(){
											//console.log($('#'+App.idIndicatorLast).width());
											var widthObject = $('#'+App.idIndicatorLast).width()/2;
											//console.log(widthObject);
											//console.log($('#rootContainer').width()); 
											var widthCanvas = $('#rootContainer').width()/2;
											//console.log(widthCanvas);
											
											var posWidth = widthCanvas - widthObject;
											$('#'+App.idIndicatorLast).css('left', posWidth); 
											
											var content =  $('#text_content_'+App.idIndicatorLast).html(); 
											var objectJson = {"content":content,"id": App.idIndicatorLast, "posy": $('#'+App.idIndicatorLast).css('top'), "posx": posWidth, "height": $('#'+App.idIndicatorLast).height(), "width": $('#'+App.idIndicatorLast).width() };
											
											App.positionAlign.top = $('#'+App.idIndicatorLast).css('top');
											App.positionAlign.left = posWidth; 
											
											var url = App.baseUrl+"CommHub/update_object_property";
											var newData = {
															"file_id": App.fileId,
															"page_id":App.pageId,
															"object_json":JSON.stringify(objectJson),
														  };
													
											var req = $.ajax({
												type: 'POST',
												url: url,
												data:newData
											});
											req.done(function(msg){
												App.socket.emit('cm_update', {roomid: App.fileId, coordinate: App.positionAlign, id: App.userId,objId:App.idIndicatorLast });
												//console.log(msg);
												// App.actionStack.push(msg.history);
												
												App.currentStackIndex++;
												App.actionStack[App.currentStackIndex] = parsedObject.history;
												
											});
										} 
							},
							{ 	text: App.localize("%context_aligment_vertical"),  
								
								alias: "vertical", 
								action: function(){
											//console.log($('#'+App.idIndicatorLast).height());
											var heightObject = $('#'+App.idIndicatorLast).height()/2;
											//console.log(heightObject);
											//console.log($('#rootContainer').height()); 
											var heightCanvas = $('#rootContainer').height()/2;
											//console.log(heightCanvas);
											
											var posHeight = heightCanvas - heightObject;
											$('#'+App.idIndicatorLast).css('top', posHeight);
											
											var content =  $('#text_content_'+App.idIndicatorLast).html(); 
											var objectJson = {"content":content,"id": App.idIndicatorLast, "posy": posHeight, "posx": $('#'+App.idIndicatorLast).css('left'), "height": $('#'+App.idIndicatorLast).height(), "width": $('#'+App.idIndicatorLast).width() }; 
											
											App.positionAlign.top = posHeight;
											App.positionAlign.left = $('#'+App.idIndicatorLast).css('left');
											
											var url = App.baseUrl+"CommHub/update_object_property";
											var newData = {
															"file_id": App.fileId,
															"page_id":App.pageId,
															"object_json":JSON.stringify(objectJson),
														  };
													
											var req = $.ajax({
												type: 'POST',
												url: url,
												data:newData
											});
											req.done(function(msg){
												App.socket.emit('cm_update', {roomid: App.fileId, coordinate: App.positionAlign, id: App.userId,objId:App.idIndicatorLast });
												//console.log(msg);
												// App.actionStack.push(msg.history);
												
													App.currentStackIndex++;
													App.actionStack[App.currentStackIndex] = parsedObject.history;
												
											});
										} 
							}
						]
						},
						{ text: App.localize("%context_arrange"), icon: "", alias: "arrange", type: "group", width: 200, items: [
							{ 	text: App.localize("%context_arrange_to_front"), 
								alias: "bring-to-front", 
								action: function(){
											App.bringToFront();
										} 
							},
							{ 	text: App.localize("%context_arrange_to_back"), 
								alias: "send-to-back", 
								action: function(){
											App.sendToBack();
										} 
							}
						]
						},
						], 
						onShow:  function (menu) { 
							menu.applyrule({ name: "all",
									disable: true,
									items: []
								}); 
							menu.disable("setback",true);
							if(App.isModeArea == 0){  
								$('#cmroot').css('width', '0px');
								$('#cmroot').css('border', '0px'); 
								$('.b-m-split').css('display', 'none');
								// menu.disable("2prevMov",true);
								// menu.disable("2avPut",true);
								menu.disable("2notTouch",true);
								menu.disable("setback",true);
								menu.disable("alignment-1",true);
								menu.disable("horizontal",true);
								menu.disable("vertical",true);
								menu.disable("lock_desc",true);
								menu.disable("edit",true);
								menu.disable("delete",true);
								menu.disable("copy",true);  
								menu.disable("unlock",true);
								menu.disable("arrange",true);
								menu.disable("bring-to-front",true);
								menu.disable("send-to-back",true);
								menu.disable("lock-1",true);
								menu.disable("setback",true);
								menu.disable("dl_attach",true);
							}else
							{ 
								$('#cmroot').css('width', '150px');
								$('.b-m-split').css('display', 'block'); 
								
								menu.disable("dl_attach",true);
								var lockStatus = App.getLockStatus($(this).attr('id'));
								if(!lockStatus)
								{
									// alert($(this).attr('is-template'));
									if($(this).attr('is-template') != 1){
										menu.disable("unlock",true);
										// menu.disable("2prevMov",false);
										// menu.disable("2avPut",false);
										menu.disable("2notTouch",false); 
										menu.disable("lock-1",false);
										// menu.disable("setback",false);
										menu.disable("alignment-1",false);
										menu.disable("horizontal",false);
										menu.disable("lock_desc",true);
										menu.disable("vertical",false);
										menu.disable("edit",false);
										menu.disable("delete",false);
										menu.disable("copy",false);   
										menu.disable("arrange",false);
										menu.disable("bring-to-front",false);
										menu.disable("send-to-back",false);
										// menu.disable("dl_attach",true);	
									}else{
										menu.disable("copy",false); 
										menu.disable("2notTouch",true);
										menu.disable("setback",true);
										menu.disable("alignment-1",true);
										menu.disable("horizontal",true);
										menu.disable("vertical",true);
										menu.disable("lock_desc",true);
										menu.disable("edit",true);
										menu.disable("delete",true);
										// menu.disable("copy",true);  
										menu.disable("unlock",true);
										menu.disable("arrange",true);
										menu.disable("bring-to-front",true);
										menu.disable("send-to-back",true);
										menu.disable("lock-1",true);
										menu.disable("setback",true);										
										// menu.disable("dl_attach",true);	
										$('.b-m-split').css('display', 'none'); 										
									}
								}
								else
								{
									// menu.disable("2prevMov",true);
									// menu.disable("2avPut",true);
									menu.disable("2notTouch",true); 
									
									if(lockStatus == App.lockEnum.MOVEMENT)
									{
										// menu.disable("setback",false);
										menu.disable("alignment-1",true);
										menu.disable("horizontal",true);
										menu.disable("vertical",true);
										menu.disable("edit",false);
										menu.disable("delete",false);
										menu.disable("lock_desc",false);
										menu.disable("copy",false);   
										menu.disable("arrange",true);
										menu.disable("bring-to-front",true);
										menu.disable("send-to-back",true);
										menu.disable("lock-1",false);
									}
									else if(lockStatus == App.lockEnum.EDIT)
									{
										// menu.disable("setback",false);
										menu.disable("alignment-1",false);
										menu.disable("horizontal",false);
										menu.disable("vertical",false);
										menu.disable("lock_desc",false);
										menu.disable("edit",true);
										menu.disable("delete",false);
										menu.disable("copy",false);   
										menu.disable("arrange",false);
										menu.disable("bring-to-front",false);
										menu.disable("send-to-back",false);
										menu.disable("lock-1",false);
									}
									else if(lockStatus == App.lockEnum.ALL)
									{
										menu.disable("setback",true);
										menu.disable("alignment-1",true);
										menu.disable("horizontal",true);
										menu.disable("vertical",true);
										menu.disable("edit",true);
										menu.disable("delete",true);
										menu.disable("lock_desc",false);
										menu.disable("copy",true);   
										menu.disable("arrange",true);
										menu.disable("bring-to-front",true);
										menu.disable("send-to-back",true);
										menu.disable("lock-1",true);
									}
									if(App.getLockerId($(this).attr('id')) == App.userId){
										menu.disable("unlock",false);
										menu.disable("lock-1",false);
										menu.disable("lock_desc",true);
										
									}
									else{
										menu.disable("unlock",true);
										menu.disable("lock-1",true);
										menu.disable("lock_desc",false);
									}
									return false;
								
								}
								if($(this).attr('object_type') == "attach"){
									menu.disable("dl_attach",false);
									menu.disable("copy",true);
									menu.disable("edit",true);
								}
								//set background munculkan hanyadi image RHEO
								if($(this).attr('object_type') == "image" || $(this).attr('object_type') == "stamp" || $(this).attr('object_type') == "shape"){
									menu.disable("setback",false);
								}
							}
							
							//hide align
								menu.disable("alignment-1",true);
						},
						
						onContextMenu: function() {
							if(App.openedTool)
							{
								alert(App.localize("%finish_action"));
								return false;
							}
							if(App.getLockStatus($(this).attr('id')) == App.lockEnum.SELECT && App.getLockerId($(this).attr('id')) != App.userId)
							{
								// var locker = App.getLockerUsername($(this).attr('id'));
								// if(!locker)
									// alert(App.localize("%locked_object_desc"));
								// else
									// alert(App.localize("%lock_edited")+locker);
								return false;
							}
							if(App.isModeArea == 1 && !App.getLockStatus($(this).attr('id')))
							{
								App.socket.emit('cm_select_object', {
									roomId: App.fileId, 
									pageId: App.pageId, 
									userId: App.userId,
									username: App.username,
									objectId:$(this).attr('id') 
								});
								App.switchActiveObject($(this));
							}
							if(App.getLockerId($(this).attr('id')) == App.userId)
							{
								App.activeObject = $(this);
							}
							return this.id != "target3";
						}
		};  
             
            
		 
			$('#rootContainer').css('background-image', 'url(' + App.baseUrl+'documents/'+App.fileId+'/background-'+ App.pageId +'.png?rnd='+Math.random()+' )');
			$('#rootContainer').css('background-size', '100%');
			//--image-background     
				
			$('.kineticjs-content').children().css('-moz-opacity','0.5');                                 
			$('.kineticjs-content').children().css('-khtml-opacity','0.5');                                 
			$('.kineticjs-content').children().css('opacity','0.5');                                 
			$('.kineticjs-content').children().css('filter','alpha(opacity=50)');  
	
		},
		ListObject:function(lockObject,statusObject, typeObject, createObjectBy, createObjectDate){
			return {
			  lockObject:lockObject,
			  statusObject:statusObject,
			  typeObject:typeObject,
			  createObjectBy:createObjectBy,
			  createObjectDate:createObjectDate
			}
		},
		
		toggle_visibility:function(id){
			$('#'+id).toggle();
		},
		deletepage: function(){
			// if(App.isModeArea == 1){
				if(App.isTemplate)
				{
					return;
				}
				if(App.pages.length <= 1)
				{
					alert(App.localize("%page_delete_error_dialog"));
					return;
				}
				var r=confirm(App.localize("%delete_page_confirmation"));
				if (r==true)
				{
					App.updatingThumbnail=true;
					$("#overlay").show();
					var url = App.baseUrl+"CommHub/delete_page";
					var data = {
						"page_id":  App.pageId,
						"file_id":  App.fileId
					};
					
					//Delete page on database
					var request=$.ajax({
						type: 'POST',
						url: url,
						data:data,
					});	
					request.done(function(msg) {
						if(msg)
						{
							//Menentukan page yang di delete
							var index =-1;
							for(var i =0;i<App.pages.length;i++)
							{
								if(App.pages[i].attr('page-id') == App.pageId)
								{
									index = i;
									break;
								}
							}
							//alert("Deleted Index : " + index);
						
							App.pages.splice(index, 1);
							$('.layerboxContainer').children().each(function(e){
								if($(this).attr('page-id') == App.pageId)
								{
									$(this).remove();
								}
							});
							var newArrangement=[];
							for(var i =0;i<App.pages.length;i++)
							{
								if(i >= index)
								{
									var prevPageId = App.pages[i].attr('page-id');
									App.pages[i].attr('page-id',parseInt(prevPageId)-1);
									// App.pages[i].find().attr({ 'src': App.baseUrl+"documents/"+App.fileId+"/thumb-"+App.pages[i].attr('page-id')+".png" , "width":"80px", "height":"60px"});
									
									var timeStamped = App.baseUrl+"documents/"+App.fileId+"/thumb-"+App.pages[i].attr('page-id')+".png?ts="+(new Date).getTime();
									var imageElement = App.pages[i].children();
									imageElement.attr('src',timeStamped)
												.attr('width',"80px")
												.attr('height',"60px");
								}
								newArrangement.push(App.pages[i].attr('page-id'));
								
							}
							App.socket.emit('cm_delete_page', {
								pageId: App.pageId, 
								roomId: App.fileId,
								newArrangement: newArrangement,
							});	
							App.pages[0].trigger('click');
							App.pageId=App.pages[0].attr('page-id');
							App.pageCount--;
							
							App.updateFileTitle();
							
							App.updatingThumbnail=false;
						}
					});
					request.always(function(jqXHR, textStatus) {
						$("#overlay").hide();
						App.updatingThumbnail=false;
					});
				}
			// }
			// else{
				// alert(App.localize("%view_mode_warning_dialog"));
			// }	
		},
		loadChatHistory:function(){
			var url = App.baseUrl+"CommHub/poll_chat_history";
			var data = {
				"file_id":  App.fileId
			};	
			var request=$.ajax({
				type: 'POST',
				url: url,
				data:data,
			});	
			request.done(function(msg) {
				var obj = JSON.parse(msg);
				for (var i=0;i<obj.content.length;i++){ 
					if(App.username == obj.content[i].username)
						$("#chat_div").chatbox("option", "boxManager").addMsg(obj.content[i].username, obj.content[i].message,true);
					else
						$("#chat_div").chatbox("option", "boxManager").addMsg(obj.content[i].username, obj.content[i].message,false);
				}
			});
		},
		
		
		//Load Object From Server
		loadCanvas: function(){
			var url = App.baseUrl+"CommHub/get_file_data";
			var allData = {"file_id": App.fileId}
			
			var request = $.ajax({ //get data awal
				url: url,
				type: "POST",
				data: allData,
			});
			request.done(function(msg) {
			//console.log("Load canvas");
				var jsonObject = JSON.parse(msg); 
				var contentObject = JSON.parse(jsonObject.content);
				//console.log(jsonObject.content);
				App.lastUpdateTime=jsonObject.last_update;
				var objectArray=[];
				
				var truncFileName=filename;
				if(truncFileName.length > 17)
				{
					truncFileName=truncFileName.substring(0,17);
							truncFileName+="...";
				}
				App.pageCount = contentObject.pages.length;
				App.updateFileTitle();
				for(var pageIndex=0;pageIndex<contentObject.pages.length;pageIndex++)
				{	
					// App.loadPageObject(contentObject.pages[pageIndex]);//, contentObject.pages[pageIndex].drawing_objects);
					// //console.log(contentObject.pages[0].drawing_objects.length);
					if(pageIndex == 0){
						//$('.file_title').width(contentObject.pages[0].width);
						$('#rootContainer').width(contentObject.pages[0].width);
						$('#rootContainer').height(contentObject.pages[0].height);
						
							App.canvasWidth=contentObject.pages[0].width;
							App.canvasHeight=contentObject.pages[0].height;
						for(var objectIndex=0;objectIndex<contentObject.pages[0].drawing_objects.length;objectIndex++)
						{
							if((contentObject.pages[0].drawing_objects[objectIndex]).type=="image")
								App.loadDrawingObject(contentObject.pages[0].drawing_objects[objectIndex]);
							if((contentObject.pages[0].drawing_objects[objectIndex]).type=="attach")
								App.loadDrawingObject(contentObject.pages[0].drawing_objects[objectIndex]);
							if((contentObject.pages[0].drawing_objects[objectIndex]).type=="text" || 
								(contentObject.pages[0].drawing_objects[objectIndex]).type=="buble" || 
								(contentObject.pages[0].drawing_objects[objectIndex]).type=="sticky-text")
								App.loadTextObject(contentObject.pages[0].drawing_objects[objectIndex]);
							if((contentObject.pages[0].drawing_objects[objectIndex]).type=="chart")
								App.loadChartObject(contentObject.pages[0].drawing_objects[objectIndex]);
							// if((contentObject.pages[0].drawing_objects[objectIndex]).type=="sticky-text")
								// App.loadStickyTextObject(contentObject.pages[0].drawing_objects[objectIndex]);
							if((contentObject.pages[0].drawing_objects[objectIndex]).type=="table")
								App.loadTableObject(contentObject.pages[0].drawing_objects[objectIndex]);
						}
					}	  
					App.loadPageObject(contentObject.pages[pageIndex]);
					
				}
				// setTimeout( App.pollServer, App.pollInterval );
				App.refreshPage = true;
				if(App.creationKind != "shape")
					App.htmlToImage(App.pageId)
				

				$("#overlay").hide();
				App.socket.emit('cm_auth', {roomid: App.fileId, page: App.pageId, username: App.username, userid: App.userId});				
			});
			request.fail(function(jqXHR, textStatus) {
			});
			request.always(function(){
			});
		},
		
		loadTextObject:function(data){
			var style = "";
			var color = "";
			if(data.object_type == "buble"){
				if(data.kind){
					if(data.kind == "bubble1"){
						style = 'class="triangle-border"';
					}else if(data.kind == "bubble2"){
						style = 'class="triangle-border right"';
					}else if(data.kind == "bubble3"){
						style = 'class="triangle-border top"';
					}else if(data.kind == "bubble4"){
						style = 'class="triangle-border left"';
					}else if(data.kind == "bubble5"){
						style = 'class="triangle-border right"';
					}else{
						style = 'class="triangle-border"';
					}
				}else{
					style = 'class="triangle-border"';
				}
			}else if(data.object_type == "sticky-text"){
				style = 'class="sticky taped"';
				color = '#F4F39E';
				if(data.kind){
					if(data.kind == "sticky2"){
						color = '#d6f0fa';
					}else if(data.kind == "sticky3"){
						color = '#f5d1f5';
					}else if(data.kind == "sticky4"){
						color = '#cffdc9';
					}else if(data.kind == "sticky5"){
						color = '#d5cdfe';
					}
				}
			}
			var newTextObject =  $('<div ' + style + '></div>')
									.attr("id",data.id)
									.attr("object_type",data.object_type)
									.addClass("nic-edit-element").appendTo($('#rootContainer'))
									.css("overflow","visible")
									.css("z-index","18")
									.attr("kind",data.kind);
			if(data.object_type == "sticky-text")
			{
				newTextObject.css("background-color",color);
			}
			
			App.Util.setBasicDimension(newTextObject,data.posx,data.posy,data.width,data.height);
			
			newTextObject.html("<div id='text_content_"+data.id+"' style='overflow:hidden;width:100%;height:100%;'>" + data.content + "</div>");
			$("#"+data.id).css("position", "");
			
			// newTextObject.on('dbltap',function() {
				// if(App.isModeArea == 1 && !data.isTemplate)
					// App.richText.enterEditMode($(this).attr('id'));
			// }); 
			
			App.addCreatorNote(newTextObject,data);
			
			App.setupObjectEvent(newTextObject,data);
		},
		
		loadStickyTextObject:function(data){
			var newStickyTextObject =  $('<div></div>')
									.attr("id",data.id)
									.attr("object_type",data.object_type)
									.addClass("nic-sticky-edit-element").appendTo($('#rootContainer'))
									.css("overflow","visible")
									.css("background",data.background)
									.css("z-index","18");
			App.Util.setBasicDimension(newStickyTextObject,data.posx,data.posy,data.width,data.height);
			
			newStickyTextObject.html("<div id='text_content_"+data.id+"' style='overflow:hidden;width:100%;height:100%;' >" + data.content + "</div>");
			$("#"+data.id).css("position", "");
			// newStickyTextObject.on('dblclick',function() {
				// if(App.isModeArea == 1 && !data.isTemplate)
				// App.richText.enterEditMode($(this).attr('id'));
			// });
			
			App.addCreatorNote(newStickyTextObject,data);
			
			App.setupObjectEvent(newStickyTextObject,data);
		},
		
		loadDrawingObject : function(data){  
			var newImgContainer = $('<div></div>')
			.attr({'id':data.id,'class':'image', 'type':data.type, 'object_type':data.type, 'created_by':data.created_by, 'created_date':data.created_date})
			.css("position","absolute")
			.css("overflow","visible")
			.css("z-index","18")
			.appendTo($('#rootContainer'));
			console.log(data.object_type);
			
			App.Util.setBasicDimension(newImgContainer,data.posx,data.posy,data.width,data.height);
		
			var newImgComponent = $('<img></img>')
			.attr({ 'src': App.baseUrl+data.image_url,'id':"img"+data.id})
			.appendTo(newImgContainer);
			 
			App.addCreatorNote(newImgContainer,data);
			if(data.object_type == "attach"){
				newImgContainer.attr("content_file",data.content_file);
				newImgContainer.on('dblclick',function() {
					window.open(App.baseUrl+data.content_file, 'Download');
				});
			}
								
			App.setupObjectEvent(newImgContainer,data);
			
		},
		
		loadTableObject:function(data){
		
			var newTableContainer = $('<div></div>')
			.attr({'id':data.id,'class':'table','type':data.type, 'object_type':data.object_type, 'border_style':data.border_style})
			.attr("bd-style",data.style)
			.attr("thickness",data.thickness)
			.css("overflow","visible")
			.css("cursor", 'default')
			.css("border", '1px solid rgb(160, 160, 164)')
			.css("position","absolute")  
			.css("z-index","18")
			.appendTo($('#rootContainer'));
		
			App.Util.setBasicDimension(newTableContainer,data.posx,data.posy,data.width,data.height);
		 
			var tableConteiner = $('<table></table>')
			.attr({ id: "tbl_"+data.id, border:"2px", width:"100%", height:"100%"})
			.html(data.content_table)
			.css('border',data.border_style)
			.appendTo(newTableContainer);
			
			App.widthMinTable = 15*data.row_table;
			App.heightMinTable = 15*data.col_table;
			
			App.addCreatorNote(newTableContainer,data);
			
			App.setupObjectEvent(newTableContainer,data);
		},
		
		loadChartObject : function(data){
		
			var newChartContainer = $('<div></div>')
			.attr({'id':data.id,'class':'image','type':data.type, 'object_type':data.object_type, 'chart-data':data.data_chart, 'type_chart':data.type_chart, 'color1':data.color1, 'color2':data.color2, 'color3':data.color3, 'scale':data.scale, 'gradient':data.gradient})
			.css("position","absolute")
			.css("overflow","visible")
			.css("z-index","18")
			.appendTo($('#rootContainer'));
			App.Util.setBasicDimension(newChartContainer,data.posx,data.posy,data.width,data.height);
			
			var newChartImgContainer = $('<img></img>')
			.attr({ 'src': App.baseUrl+data.image_url,'id':"img"+data.id})
			.appendTo(newChartContainer);
			
			App.addCreatorNote(newChartContainer,data);
			
			App.setupObjectEvent(newChartContainer,data);
	
		},
		  
		loadPageObject : function(data){
			console.log(data);
			//alert("Prepare to add layer");
			var newPageContainer = $('<div></div>').attr({'class':'layerbox','page-id':data.id}).appendTo($('.layerboxContainer'));
			console.log(newPageContainer); 
			if(data.id == 1){
				newPageContainer.css('border','2px solid yellow');
				App.activeObject=newPageContainer;
			}else{
				newPageContainer.css('border','2px solid #888888');		 
			}
			
			var newPageImgComponent = $('<img></img>').attr({ 'src': App.baseUrl+"documents/"+App.fileId+"/thumb-"+data.id+".png" , "width":"80px", "height":"60px"}).appendTo(newPageContainer);
			
			newPageContainer.on('click',function(){
						if(App.openedTool)
						{
							alert(App.localize("%finish_action"));
							return;
						}
						//reset undo/redo stack
						
						App.currentStackIndex=-1;
						App.actionStack = [];
						$("#overlay").show(); 
						 if(App.activeObject)
						{
							App.socket.emit('cm_deselect_object', {
									roomId: App.fileId, 
									pageId: App.pageId, 
									userId: App.userId,
									username: App.username,
									objectId:App.activeObject.attr('id') 
							});
							App.socket.emit('cm_unlock', {
								roomid: App.fileId,
								pageid:App.pageId,
								status:App.lockEnum.SELECT,
								objectId: App.activeObject.attr('id'), 
								id: App.userId,
								password:"", 
								without_pass:App.withoutPass
							});
						}
						$('#rootContainer').html("");
						if(isNaN(parseInt(data.width)) || isNaN(parseInt(data.height))){
							$('#rootContainer').css({"width":"970px","height":"600px"});
							App.canvasWidth=970;
							App.canvasHeight=970;
						}else{
							//$('.file_title').width(data.width);
							$('#rootContainer').css({"width":data.width+"px","height":data.height+"px"});
							App.canvasWidth=data.width;
							App.canvasHeight=data.height;
						}
						App.pageId = $(this).attr("page-id");
						
						
						if(App.idPageSelcLast == 0){
							$('.layerboxContainer').children().each(function(){
								if($(this).attr('page-id') == 1)
								{ 
									$(this).css('border','2px solid #888888');
								} 
							}); 
						}
					
						for(var i =0;i<App.pages.length;i++)
						{
							if(App.pages[i].attr('page-id') == App.idPageSelcLast)
							{
								App.pages[i].css('border','2px solid #888888');
								break;
							}
						}
						App.updateFileTitle();
						var url = App.baseUrl+"CommHub/get_data_page";
						var allData = {"file_id": App.fileId,
										"page_id":App.pageId,}
						
						var request = $.ajax({ //get data awal
							url: url,
							type: "POST",
							data: allData,
						});
						request.done(function(msg) {
							
							var jsonObject = JSON.parse(msg); 
							
							for(var objectIndex=0;objectIndex<jsonObject.drawing_objects.length;objectIndex++)
							{
								if((jsonObject.drawing_objects[objectIndex]).type=="image")
									App.loadDrawingObject(jsonObject.drawing_objects[objectIndex]);
								if((jsonObject.drawing_objects[objectIndex]).type=="attach")
									App.loadDrawingObject(jsonObject.drawing_objects[objectIndex]);
								if((jsonObject.drawing_objects[objectIndex]).type=="text" ||
									(jsonObject.drawing_objects[objectIndex]).type=="buble" ||
									(jsonObject.drawing_objects[objectIndex]).type=="sticky-text")
									App.loadTextObject(jsonObject.drawing_objects[objectIndex]);
								if((jsonObject.drawing_objects[objectIndex]).type=="chart")
									App.loadChartObject(jsonObject.drawing_objects[objectIndex]);
								// if((jsonObject.drawing_objects[objectIndex]).type=="sticky-text")
									// App.loadStickyTextObject(jsonObject.drawing_objects[objectIndex]);
								if((jsonObject.drawing_objects[objectIndex]).type=="table")
									App.loadTableObject(jsonObject.drawing_objects[objectIndex]);
							} 
							$('#rootContainer').css('background-image', 'url(' + App.baseUrl+'documents/'+App.fileId+'/background-'+ App.pageId +'.png?rnd='+Math.random()+' )');
							$('#rootContainer').css('background-size', '100%');
							$("#overlay").hide();
							App.applyLock(App.lockedObjectList);
							App.activeObject =false;
							App.propertyToolbox.heightGrid=0;
							App.propertyToolbox.isGrid=0;
							App.propertyToolbox.isDashed=0;
							
							
							//Firman : Updating Thumbnail
							App.htmlToImage(App.pageId);
						});
						request.fail(function(jqXHR, textStatus) {
						});
						request.always(function(){
						});
						
						 
					 
				$(this).css("border", "2px solid yellow");
				App.idPageSelcLast=$(this).attr('page-id');
			}); 
			App.pages.push(newPageContainer);
		},	
		updateObjectProperty:function(){
			
		},
		disableclick:function(e){
			if(e.button==2)
			{
				return false;    
			}
		},
		putObjectOnRoot: function(img){
		
		},
		
		addTextToServer:function(text){
			var d = new Date();
			var strDate = d.getDate() + "/" + (d.getMonth()+1) + "/" + d.getFullYear(); 
			var url = App.baseUrl+"CommHub/add_text/";
			var width;
			var height;
			if(App.creationKind == "buble"){
				if(App.creationType){
					if(App.creationType == "bubble1"){
						width = 200;
						height = $("#"+text.id).height();
					}else if(App.creationType == "bubble2"){
						width = 200;
						height = $("#"+text.id).height();
					}else if(App.creationType == "bubble3"){
						width = 230;
						height = 30;
					}else if(App.creationType == "bubble4"){
						width = 230;
						height = 30;
					}else if(App.creationType == "bubble5"){
						width = 200;
						height = $("#"+text.id).height();
					}else{
						width = $("#"+text.id).width();
						height = $("#"+text.id).height();
					}
				}else{
					width = $("#"+text.id).width();
					height = $("#"+text.id).height();
				}
			}else{
				width = $("#"+text.id).width();
				height = $("#"+text.id).height();
			}
			var allData = {
							"file_id":App.fileId,
							"page_id":App.pageId,
							"id": text.id,
							"object_id": text.id,
							"content": $("#"+text.id).html(),
							"posx": $("#"+text.id).position().left,
							"posy": $("#"+text.id).position().top,
							"width": width,
							"height": height,
							"kind" : App.creationKind,
							"username":App.username,
							"curr_date":strDate,
							"type": App.creationType
							};
			var request =$.ajax({
				type: 'POST',
				url: url,
				data:allData
			});
			request.done(function(msg) {
				App.richText.menu.cancel();
				App.stickyText.menu.cancel();
				App.creationMode = false;
				App.prepareCreation = false;
				App.creationKind = false;
				App.creationShape = false;
				var parsedObject = JSON.parse(msg);
				
				App.currentStackIndex++;
				App.actionStack[App.currentStackIndex] = parsedObject.history;
				parsedObject = JSON.parse(parsedObject.message);
				
				parsedObject.kind = App.creationType;
				App.loadTextObject(parsedObject);

				App.socket.emit('cm_new', {roomid: App.fileId,pageid:App.pageId,  object:parsedObject, id: App.userId,objId:$(this).attr('id'),type:"text" }); 
				
				
			});
			request.fail(function(jqXHR, textStatus) {
			});
			request.always(function(){
			});
		},
		
		addStickyTextToServer:function(text){
			var d = new Date();
			var strDate = d.getDate() + "/" + (d.getMonth()+1) + "/" + d.getFullYear(); 
		
			var textId = (new Date).getTime();
			var url = App.baseUrl+"CommHub/add_sticky_text/";
			var allData = {
							"file_id":App.fileId,
							"page_id":App.pageId,
							"id": text.id,
							"object_id": text.id,
							"content": $("#"+text.id).html(),
							"posx": $("#"+text.id).position().left,
							"posy": $("#"+text.id).position().top,
							"width": $("#"+text.id).width(),
							"height": $("#"+text.id).height(),
							"background": $("#"+text.id).css("background-color"),
							"username":App.username,
							"curr_date":strDate
							};
			var request =$.ajax({
				type: 'POST',
				url: url,
				data:allData
			});
			request.done(function(msg) {
				App.richText.menu.cancel();
				App.stickyText.menu.cancel();
				App.creationMode = false;
				App.prepareCreation = false;
				App.creationKind = false;
				App.creationShape = false;
				var parsedObject = JSON.parse(msg);
				
				App.currentStackIndex++;
				App.actionStack[App.currentStackIndex] = parsedObject.history;
				
				parsedObject = JSON.parse(parsedObject.message);
				
				
				App.loadStickyTextObject(parsedObject);
				App.socket.emit('cm_new', {roomid: App.fileId, pageid:App.pageId, object:parsedObject, id: App.userId,objId:$(this).attr('id'),type:"sticky-text" }); 
				
			});
			request.fail(function(jqXHR, textStatus) {
			});
			request.always(function(){
			});
		},
		
		addObjectToServer:function(image,posx,posy,objTyp){
			var d = new Date();
			var strDate = d.getDate() + "/" + (d.getMonth()+1) + "/" + d.getFullYear();
			var imgId = (new Date).getTime();
			var filepath = "documents/"+App.fileId+"/"+imgId+".png";
			var url = App.baseUrl+"CommHub/add_object/";
			var allData = {
							"image_data":image,
							"file_id":App.fileId,
							"page_id":App.pageId,
							"id": imgId,
							"filepath":filepath,
							"posx":posx,
							"posy":posy,
							"obj_type":objTyp,
							"username":App.username,
							"curr_date":strDate
							};
			var request =$.ajax({
				type: 'POST',
				url: url,
				data:allData
			});
			request.done(function(msg) {
				var parsedObject = JSON.parse(msg);
				
				App.currentStackIndex++;
				App.actionStack[App.currentStackIndex] = parsedObject.history;
				parsedObject = JSON.parse(parsedObject.message);
				App.loadDrawingObject(parsedObject);
	
				App.socket.emit('cm_new', {roomid: App.fileId,pageid:App.pageId, object:parsedObject, id: App.userId,objId:$(this).attr('id'),type:"image" }); 
				
			});
			request.fail(function(jqXHR, textStatus) {
			});
			request.always(function(){
			});
		},
		updateImage:function(image,posx,posy,objTyp,oldId){
			var d = new Date();
			var strDate = d.getDate() + "/" + (d.getMonth()+1) + "/" + d.getFullYear();
			var imgId = (new Date).getTime();
			var filepath = "documents/"+App.fileId+"/"+imgId+".png";
			var url = App.baseUrl+"CommHub/update_image/";
			var allData = {
							"image_data":image,
							"file_id":App.fileId,
							"page_id":App.pageId,
							"id": imgId,
							"old_id": oldId,
							"filepath":filepath,
							"posx":posx,
							"posy":posy,
							"obj_type":objTyp,
							};
			var request =$.ajax({
				type: 'POST',
				url: url,
				data:allData
			});
			request.done(function(msg) {
				var parsedObject = JSON.parse(msg);
				
				App.currentStackIndex++;
				App.actionStack[App.currentStackIndex] = parsedObject.history;
				parsedObject = JSON.parse(parsedObject.message);
				console.log(parsedObject);
				App.loadDrawingObject(parsedObject);
	
				App.socket.emit('cm_update_image', {roomid: App.fileId,pageid:App.pageId, object:parsedObject, id: App.userId,objId:parsedObject.id,image_url:parsedObject.image_url }); 
				
			});
			request.fail(function(jqXHR, textStatus) {
			});
			request.always(function(){
			});
		},
		addObjectToServerImageEditing:function(image,posx,posy,objTyp,oldId){
			App.showLoading();
			var d = new Date();
			var strDate = d.getDate() + "/" + (d.getMonth()+1) + "/" + d.getFullYear();
			var imgId = oldId;
			var filepath = "documents/"+App.fileId+"/"+imgId+".png";
			var url = App.baseUrl+"CommHub/add_object/";
			var allData = {
							"image_data":image,
							"file_id":App.fileId,
							"page_id":App.pageId,
							"id": imgId,
							"filepath":filepath,
							"posx":posx,
							"posy":posy,
							"obj_type":objTyp,
							"username":App.username,
							"curr_date":strDate
							};
			var request =$.ajax({
				type: 'POST',
				url: url,
				data:allData
			});
			request.done(function(msg) {
				var parsedObject = JSON.parse(msg);
				parsedObject = JSON.parse(parsedObject.message);
				App.loadDrawingObject(parsedObject);
	
				App.socket.emit('cm_new', {roomid: App.fileId,pageid:App.pageId, object:parsedObject, id: App.userId,objId:$(this).attr('id'),type:"image" }); 
				
			});
			request.fail(function(jqXHR, textStatus) {
			});
			request.always(function(){
			});
		},
		
		prepareTextCreation: function(creation){
			App.prepareCreation = creation;
			App.creationKind = "text";
			App.creationType = "text";
			if(App.prepareCreation){
				var center = App.getAbsoluteCenter();
				
				if(!App.richText.menu.isShow){
					App.richText.menu.show();
					App.richText.createObject(center);
				}
			}
		},
		
		prepareBubleTextCreation: function(creation,type){
			App.prepareCreation = creation;
			App.creationKind = "buble";
			App.creationType = type;
			if(App.prepareCreation){
				var center = App.getAbsoluteCenter();
				App.bubbleToolbox.hide();
					
				if(!App.richText.menu.isShow){
					App.richText.menu.show();
					App.richText.createObject(center);
				}
				
			}
		},
		
		prepareStickyTextCreation: function(creation,type){
			App.prepareCreation = creation;
			App.creationKind = "sticky-text";
			App.creationType = type;
			if(App.prepareCreation){
				var center = App.getAbsoluteCenter();
				App.stickyToolbox.hide();
					
				if(!App.richText.menu.isShow){
					App.richText.menu.show();
					App.richText.createObject(center);
				}				
			}
		},
		
		setEnableKineticCreationMode: function(creation,shouldSave){
			App.creationMode = creation;
			App.kinetic.editMode = false;
			if(App.creationMode){
				// document.getElementById(App.rootCanvas).style.display = "none";
				document.getElementById(App.kineticCanvas).style.display = "block";
				// App.kinetic.setStageSize({width:970,height:600});
				App.kinetic.setStageSize({width:(parseInt(App.canvasWidth)+110),height:(parseInt(App.canvasHeight)+130)});
				$("#" + App.kineticCanvas).css({"border":"1px solid black","width":(parseInt(App.canvasWidth)+110),"height":(parseInt(App.canvasHeight)+130),"top":"20px","left":"0px","position":"absolute"});
				// $("#" + App.kineticCanvas).offset({top:110,left:130});
				App.kinetic.enterCreationMode();
				
			}else{
				// document.getElementById(App.rootCanvas).style.display = "block";
				document.getElementById(App.kineticCanvas).style.display = "none";
				App.kinetic.endCreationMode(shouldSave);
			}
		},
		
		setEnableKineticEditCreationMode: function(creation,shouldSave){
			//console.log("Enable Kinetic Mode For Edit");
			App.kinetic.editMode = true;
			App.creationMode = creation;
			if(App.creationMode){
				App.activeObject.hide();
				App.kinetic.enterCreationMode();
				document.getElementById(App.kineticCanvas).style.display = "block";
				App.kinetic.setStageSize({width:App.editProp.width,height:App.editProp.height});
				App.kinetic.setBGCanvas(App.editProp.bgCanvas,{width:App.editProp.width,height:App.editProp.height});
				$("#" + App.kineticCanvas).css({"border":"3px solid red","width":App.editProp.width,"height":App.editProp.height});
				$("#" + App.kineticCanvas).offset({top:App.editProp.y,left:App.editProp.x});
			}else{
				if(shouldSave)
					App.activeObject.remove();
				else
					App.activeObject.show();
				document.getElementById(App.kineticCanvas).style.display = "none";
				App.kinetic.endCreationMode(shouldSave);
			}
		},
		
		setEnableStampCreationMode: function(creation,stampImage){
			App.creationMode = creation;
			if(App.creationMode)
				App.setCreationObject("stamp",stampImage);
			
		},
		
		setCreationObject : function(kind,type){
			App.creationKind = kind;
			App.creationType = type;
			//console.log("Enter Creation : " + kind + " - " + type);
		},
				
		setEnableImageCreationMode: function(creation){
			App.creationMode = creation;
			if(App.creationMode)
			{
				App.setCreationObject("image");
				App.upload.show();
			}
		},
		
		setEnableFileCreationMode: function(creation){
			App.creationMode = creation;
			if(App.creationMode)
			{
				App.setCreationObject("file");
				App.uploadFile.show();
			}
		},
		
		setEnableChartCreationMode: function(creation){
			App.creationMode = creation;
			if(App.creationMode)
			{
				App.setCreationObject("chart");
				for(var i=0;i<$.jPicker.List.length;i++)
				{
					if($.jPicker.List[i].id == "colorChart" || $.jPicker.List[i].id == "startColorChart" || $.jPicker.List[i].id == "endColorChart")
					{
						$.jPicker.List[i].color.active.val('hex', "ffcc00", this);
					}
				}
				App.chartToolbox.show();
			}
		},
		
		setEnableTableCreationMode: function(creation){
			App.creationMode = creation;
			if(App.creationMode)
			{
				App.setCreationObject("table");
				$('.style_list').removeAttr('style');
				$('.width_list').removeAttr('style');
				$('#value-row').val('1');
				$('#value-column').val('1');
				for(var i=0;i<$.jPicker.List.length;i++)
				{
					if($.jPicker.List[i].id == "label-color-table")
					{
						$.jPicker.List[i].color.active.val('hex', "000000", this);
						break;
					}
				}
				App.initialTableToolbox.show();
			}
		},
		
		setEnableTextLogoCreationMode: function(creation){
			App.creationMode = creation;
			if(App.creationMode)
				App.setCreationObject("text-logo");
		},
	
		deleteObjectById : function(object_id){
			if(typeof $('#'+object_id).attr('is-template') != 'undefined')
			{
				alert(App.localize("%delete_template_warning_dialog"));
				return;
			}
			var deletedId = object_id;
			$("#" + object_id).remove();
			App.activeObject=false;
			var url = App.baseUrl+"CommHub/delete_object/";
			var allData = {
							"file_id":App.fileId,
							"page_id":App.pageId,
							"id": deletedId,
							};
			var request =$.ajax({
				type: 'POST',
				url: url,
				data:allData
			});
			request.done(function(msg) {
				App.currentStackIndex++;
				App.actionStack[App.currentStackIndex] = msg.history;
				console.log(App.currentStackIndex);
				console.log(App.actionStack.length-App.currentStackIndex);
				App.actionStack.splice(App.currentStackIndex+1,App.actionStack.length-App.currentStackIndex);
				App.socket.emit('cm_delete', {roomid: App.fileId, deletedId: deletedId, id: App.userId,type:"object" }); 
			});
			request.fail(function(jqXHR, textStatus) {
			});
			request.always(function(){
			});
				
		},
		
		addRecoverStack : function(obj){
			obj.attr("page_id",App.pageId);
		},
		
		deleteObject:function(){	
			if(App.isModeArea == 1){
				
				if(App.activeObject)
				{
					if(typeof App.activeObject.attr('is-template') != 'undefined')
					{
						alert(App.localize("%delete_template_warning_dialog"));
						return;
					}
					if(App.getLockStatus(App.activeObject.attr('id')))
					{
						var locker = App.getLockerUsername(App.activeObject.attr('id'));
						if(!locker)
							alert(App.localize("%locked_object_desc"));
						else
							alert(App.localize("%lock_edited")+locker);
						return;
					}
					var r;
					if(App.kinetic.editMode){
						r=true;
						App.kinetic.editMode = false;
					}else{
						r=confirm(App.localize("%delete_object_confirmation"));
					}
					if (r==true)
					{  
						var clone = App.activeObject.clone();
						clone.attr("object_type",App.activeObject.attr("object_type"));
						//console.log("DELETED : " + clone.attr("object_type"));
						var deletedId = App.activeObject.attr('id');
						
						//console.log(deletedId);
						App.activeObject.remove();
						App.activeObject=false;
						
						//console.log("Deleted object with id " + deletedId);
						var url = App.baseUrl+"CommHub/delete_object/";
						var allData = {
										"file_id":App.fileId,
										"page_id":App.pageId,
										"id": deletedId,
										};
						var request =$.ajax({
							type: 'POST',
							url: url,
							data:allData
						});
						request.done(function(msg) {
							msg = JSON.parse(msg);
							App.currentStackIndex++;
							App.actionStack[App.currentStackIndex] = msg.history;
							console.log(App.currentStackIndex);
							console.log(App.actionStack.length-App.currentStackIndex);
							App.actionStack.splice(App.currentStackIndex+1,App.actionStack.length-App.currentStackIndex);
							App.socket.emit('cm_delete', {roomid: App.fileId, deletedId: deletedId, id: App.userId,type:"object" }); 
							
						});
						request.fail(function(jqXHR, textStatus) {
						});
						request.always(function(){
						});
						App.activeObject = null;
					}
					
				}
				
			}else{
				alert(App.localize("%view_mode_warning_dialog"));
			}
		},
		
		addStamp:function(stampImg,posx,posy){
			var d = new Date();
			var strDate = d.getDate() + "/" + (d.getMonth()+1) + "/" + d.getFullYear(); 
			
			//console.log(posx);
			var imgId = (new Date).getTime();
			var newStampPath = "documents/"+App.fileId+"/"+imgId+".png";
			var url = App.baseUrl+"CommHub/add_stamp/";
				
			var allData = {
					"file_id":App.fileId,
					"page_id":App.pageId,
					"id": imgId,
					"filepath":stampImg,
					"stamppath":newStampPath,
					"posx":posx,
					"posy":posy,
					"username":App.username,
					"curr_date":strDate
			};
			var request =$.ajax({
				type: 'POST',
				url: url,
				data:allData
			});
			request.done(function(msg) {
				var parsedObject = JSON.parse(msg);
				
				App.currentStackIndex++;
				App.actionStack[App.currentStackIndex] = parsedObject.history;
				parsedObject = JSON.parse(parsedObject.message);
				console.log(parsedObject);
				App.loadDrawingObject(parsedObject);
				App.socket.emit('cm_new', {roomid: App.fileId, pageid:App.pageId, object:parsedObject, id: App.userId,objId:$(this).attr('id'),type:"image" }); 
			});
			request.fail(function(jqXHR, textStatus) {
			});
			request.always(function(){
			});
		},	
		
		addUploadedImage:function(image,posx,posy){ 
			var d = new Date();
			var strDate = d.getDate() + "/" + (d.getMonth()+1) + "/" + d.getFullYear(); 
			
			var imgId = (new Date).getTime();
			var newImagePath = "documents/"+App.fileId+"/"+imgId;
			var url = App.baseUrl+"CommHub/add_uploaded_image/";
			var allData = {
					"file_id":App.fileId,
					"page_id":App.pageId,
					"id": imgId,
					"filepath":image,
					"imagepath":newImagePath,
					"posx":posx,
					"posy":posy,
					"username":App.username,
					"curr_date":strDate
			};
			var request =$.ajax({
				type: 'POST',
				url: url,
				data:allData
			});
			request.done(function(msg) {
				var parsedObject = JSON.parse(msg);
				
				App.currentStackIndex++;
				App.actionStack[App.currentStackIndex] = parsedObject.history;
				parsedObject = JSON.parse(parsedObject.message);
				App.loadDrawingObject(parsedObject);
				App.socket.emit('cm_new', {roomid: App.fileId, pageid:App.pageId, object:parsedObject, id: App.userId,objId:$(this).attr('id'),type:"image" }); 

			});
			request.fail(function(jqXHR, textStatus) {
			});
			request.always(function(){
			});
		},
		
		addUploadedFile:function(file,fileName,image,posx,posy){
			var d = new Date();
			var strDate = d.getDate() + "/" + (d.getMonth()+1) + "/" + d.getFullYear(); 
			
			var imgId = (new Date).getTime();
			var fileId = imgId;
			var contentFile = "documents/"+App.fileId+"/"+fileId+"_"+fileName;//".png";
			var newImagePath = "documents/"+App.fileId+"/"+imgId+".png";
			image = App.baseUrl+"assets/css/images/attach.png";
			var url = App.baseUrl+"CommHub/add_uploaded_file/";
			
			var allData = {
					"file_id":App.fileId,
					"page_id":App.pageId,
					"id": imgId,
					"filepath":image,
					"filepath_file":file,
					"imagepath":newImagePath,
					"posx":posx,
					"posy":posy,
					"content_file":contentFile,
					"username":App.username,
					"curr_date":strDate
			};
			var request =$.ajax({
				type: 'POST',
				url: url,
				data:allData
			});
			request.done(function(msg) { 
				//console.log(msg);
				var parsedObject = JSON.parse(msg);
				
				App.currentStackIndex++;
				App.actionStack[App.currentStackIndex] = parsedObject.history;
				parsedObject = JSON.parse(parsedObject.message);
				App.loadDrawingObject(parsedObject);
				App.socket.emit('cm_new', {roomid: App.fileId, pageid:App.pageId, object:parsedObject, id: App.userId,objId:$(this).attr('id'),type:"attach" }); 
			});
			request.fail(function(jqXHR, textStatus) {
			});
			request.always(function(){
			});
		},
		
		addChartToServer:function(dataChart,typeChart,posx,posy, wChart, hChart, fillColor){
			var d = new Date();
			var strDate = d.getDate() + "/" + (d.getMonth()+1) + "/" + d.getFullYear(); 
		 
			var imgId = (new Date).getTime();
			var fileId = imgId;
			var url = App.baseUrl+"CommHub/add_chart_fill/";
			var allData = {
					"file_id":App.fileId,
					"page_id":App.pageId,
					"id": imgId,
					"posx":posx,
					"posy":posy,
					"type_chart" : typeChart,
					"data_chart" : dataChart,
					"width_chart" : parseInt(wChart),
					"height_chart" : parseInt(hChart),
					"fill_color" : App.chartToolbox.fillColor,
					"gradient" : parseInt(App.chartToolbox.gradient),
					"axisCrd" : parseInt(App.chartToolbox.scale90),
					"gradient" : App.chartToolbox.gradient,
					"start_color" : App.chartToolbox.startColor,
					"end_color" : App.chartToolbox.endColor,
					"username":App.username,
					"curr_date":strDate
					
			};
			var request =$.ajax({
				type: 'POST',
				 url: url,
				data:allData
			});
			request.done(function(msg) {
				//console.log(msg);
				App.chartToolbox.gradient = 0;
				App.chartToolbox.scale90 = 0;
				App.chartToolbox.startColor = false;
				App.chartToolbox.endColor = false;
				App.chartToolbox.fillColor = [];
				App.chartToolbox.radioChartVal = false;
				var parsedObject = JSON.parse(msg);
				
				
				App.currentStackIndex++;
				App.actionStack[App.currentStackIndex] = parsedObject.history;
				parsedObject = JSON.parse(parsedObject.message);
				App.loadChartObject(parsedObject);
				App.socket.emit('cm_new', {roomid: App.fileId, pageid:App.pageId, object:parsedObject, id: App.userId,objId:$(this).attr('id'),type:"chart" }); 
				
			});
			request.fail(function(jqXHR, textStatus) {
			});
			request.always(function(){
			});
			return imgId;
		},
		
		pickColor:function(id){
			App.pickColorToolbox.show();
		},
		
		pickColorSelected:function(){			
			// //console.log(App.pickColorToolbox.color);
			var hex = App.pickColorToolbox.color;
			if(hex.charAt(0) == "#") hex = hex.slice(1); //Remove the '#' char - if there is one.
			hex = hex.toUpperCase();
			var hex_alphabets = "0123456789ABCDEF";
			var value = new Array(3);
			var k = 0;
			var int1,int2;
			for(var i=0;i<6;i+=2) {
				int1 = hex_alphabets.indexOf(hex.charAt(i));
				int2 = hex_alphabets.indexOf(hex.charAt(i+1)); 
				value[k] = (int1 * 16) + int2;
				k++;
			}
			//console.log(value[0]);
		},
		
		copyObject:function(){
			if(App.isModeArea == 1){
				if(App.activeObject)
				{
					if(App.getLockStatus(App.activeObject.attr('id')))
					{
						
						var locker = App.getLockerUsername(App.activeObject.attr('id'));
						if(!locker)
							alert(App.localize("%locked_object_desc"));
						else
							alert(App.localize("%lock_edited")+locker);
						return;
					}
					//console.log("DO COPY");
					//console.log(App.activeObject);
					
					var copiedId = App.activeObject.attr('id');
					
					
					var containerY = App.activeObject.css('top');
					var containerX = App.activeObject.css('left');
					var width = App.activeObject.css('width');
					var height = App.activeObject.css('height');
					var objectType = $("#"+copiedId).attr('object_type');
					//console.log(objectType);
					if(App.isRecover)
						objectType = App.activeObject.attr('object_type');
						
					if (objectType == "image")
					{	
						var imgSrc = $("#img"+copiedId).attr('src');
						
						var d = new Date();
						var strDate = d.getDate() + "/" + (d.getMonth()+1) + "/" + d.getFullYear(); 
						var imgId = (new Date).getTime();
						var filepath = "documents/"+App.fileId+"/"+copiedId+".png";
						var copypath = "documents/"+App.fileId+"/"+imgId+".png";
						var url = App.baseUrl+"CommHub/copy_object/";
						
						var allData = {
										"file_id":App.fileId,
										"page_id":App.pageId,
										"id": imgId,
										"filepath":filepath,
										"copypath":copypath,
										"posx":parseInt(containerX)+20,
										"posy":parseInt(containerY)+20,
										"width":width,
										"height":height,
										"type":"image",
										"object_type":objectType,
										"username":App.username,
										"curr_date":strDate
										};
						var request =$.ajax({
							type: 'POST',
							url: url,
							data:allData
						});
						request.done(function(msg) {
							var parsedObject = JSON.parse(msg);
							App.currentStackIndex++;
							App.actionStack[App.currentStackIndex] = parsedObject.history;
							parsedObject = JSON.parse(parsedObject.message);
							App.loadDrawingObject(parsedObject);
							App.socket.emit('cm_new', {roomid: App.fileId, pageid:App.pageId, object:parsedObject, id: App.userId,objId:$(this).attr('id'),type:parsedObject.type }); 
							
						});
						request.fail(function(jqXHR, textStatus) {
						});
						request.always(function(){
						});
					}
					else if (objectType == "text" || objectType == "buble" || objectType == "sticky-text")
					{
						var clone = $("#"+copiedId).clone();
						if(App.isRecover)
							clone = App.activeObject.clone();
							
						clone.find(".ui-resizable-handle").remove();
						clone.find('#'+copiedId+"-c").remove();
						clone.find('#context_ico_'+copiedId).remove();
						var content = $("#text_content_"+copiedId).html();
						var textId = (new Date).getTime();
						var url = App.baseUrl+"CommHub/copy_text/";
						if(objectType == "buble" || objectType == "sticky-text")
						{
							var allData = {
											"file_id":App.fileId,
											"page_id":App.pageId,
											"id": textId,
											"object_id": textId,
											"content": content,
											"posx":parseInt(containerX)+20,
											"posy":parseInt(containerY)+20,
											"width":width,
											"object_type":objectType,
											"kind":clone.attr('kind'),
											"height":height,
											"text_type":objectType
											};
						}
						else
						{
							var allData = {
											"file_id":App.fileId,
											"page_id":App.pageId,
											"id": textId,
											"object_id": textId,
											"content": content,
											"posx":parseInt(containerX)+20,
											"posy":parseInt(containerY)+20,
											"width":width,
											"object_type":objectType,
											"height":height,
											"text_type":objectType
											};
						}
						
						var request =$.ajax({
							type: 'POST',
							url: url,
							data:allData
						});
						request.done(function(msg) {
							App.richText.menu.cancel();
							App.stickyText.menu.cancel();
							App.creationMode = false;
							App.prepareCreation = false;
							App.creationKind = false;
							App.creationShape = false;
							var parsedObject = JSON.parse(msg);
							App.currentStackIndex++;
							App.actionStack[App.currentStackIndex] = parsedObject.history;
							parsedObject = JSON.parse(parsedObject.message);
							//console.log(parsedObject);
							// if(objectType == "sticky-text")
							// {
								// App.loadStickyTextObject(parsedObject);
							// }
							// else
								App.loadTextObject(parsedObject);
							App.socket.emit('cm_new', {roomid: App.fileId, pageid:App.pageId, object:parsedObject, id: App.userId,objId:$(this).attr('id'),type:objectType }); 
							
							
						});
						request.fail(function(jqXHR, textStatus) {
						});
						request.always(function(){
						});
					}
					else if (objectType == "chart")
					{	
						var dataChart = $("#"+copiedId).attr('chart-data');
						
						var chartId = (new Date).getTime();
						var filepath = $("#img"+copiedId).attr('src');
						var copypath = "temp_upload/"+chartId+".png";
						var url = App.baseUrl+"CommHub/copy_chart/";
						if(App.isRecover){
							dataChart = App.activeObject.attr('chart-data');
							filepath = App.activeObject.children("#img"+copiedId).attr('src');
						}
						var allData = {
										"file_id":App.fileId,
										"page_id":App.pageId,
										"id": chartId,
										"filepath":filepath,
										"copypath":copypath,
										"posx":parseInt(containerX)+20,
										"posy":parseInt(containerY)+20,
										"width":width,
										"height":height,
										"object_type":objectType,
										"type":"chart",
										"data_chart":dataChart
										};
						var request =$.ajax({
							type: 'POST',
							url: url,
							data:allData
						});
						request.done(function(msg) {
							var parsedObject = JSON.parse(msg);
							App.currentStackIndex++;
							App.actionStack[App.currentStackIndex] = parsedObject.history;
							parsedObject = JSON.parse(parsedObject.message);
							App.loadChartObject(parsedObject);
							App.socket.emit('cm_new', {roomid: App.fileId, pageid:App.pageId, object:parsedObject, id: App.userId,objId:$(this).attr('id'),type:parsedObject.type }); 
							
						});
						request.fail(function(jqXHR, textStatus) {
						});
						request.always(function(){
						});
					}
					else if (objectType == "table")
					{
						
						var tblId = (new Date).getTime(); 
						
						var url = App.baseUrl+"CommHub/copy_table/";
						
						var copiedTable = $('#tbl_'+copiedId);
					
						
						var allData = {
								"file_id":App.fileId,
								"page_id":App.pageId,
								"id": tblId,  
								"width":width,
								"height":height,
								"object_type":objectType,
								"posx":parseInt(containerX)+20,
								"posy":parseInt(containerY)+20,
								"content_table":copiedTable.html(),
								"copied_id":copiedId				// Add by Nanda DR 25072013 - Notes : need id object copy
						};
						var request =$.ajax({
							type: 'POST',
							url: url,
							data:allData
						});
						request.done(function(msg) {  
							var parsedObject = JSON.parse(msg);
							App.currentStackIndex++;
							App.actionStack[App.currentStackIndex] = parsedObject.history;
							parsedObject = JSON.parse(parsedObject.message);
							App.loadTableObject(parsedObject);
							App.socket.emit('cm_new', {roomid: App.fileId, pageid:App.pageId, object:parsedObject, id: App.userId,objId:$(this).attr('id'),type:parsedObject.type }); 
						});
						request.fail(function(jqXHR, textStatus) {
						});
						request.always(function(){
						});
					}
					
				}
			}else{
				alert(App.localize("%view_mode_warning_dialog"));
			}
		},
		
		bringToFront:function(){
			if(App.activeObject)
			{
				App.activeObject.removeAttr("back-layer")
				App.activeObject.css({"z-index":parseInt(App.lastZ) + 1});
				App.lastZ++;
				App.socket.emit('cm_z_index', {
						roomId: App.fileId, 
						pageId: App.pageId, 
						userId: App.userId,
						//username: App.username,
						objectId:App.activeObject.attr('id'),
						z_index:parseInt(App.lastZ)
				});
			}
			
		},
		
		sendToBack:function(){
			if(App.activeObject)
			{
				App.activeObject.css({"z-index":"10"});
				App.activeObject.attr('back-layer','1');
					
				App.socket.emit('cm_z_index', {
						roomId: App.fileId, 
						pageId: App.pageId, 
						userId: App.userId,
						//username: App.username,
						objectId:App.activeObject.attr('id'),
						z_index:"10"
				});
			}	
		},
		inBackLayer:function(object){
			return typeof object.attr('back-layer') != "undefined";
		},
		editObject:function(){
			if(App.openedTool)
			{
				alert(App.localize("%finish_tool"));
				return;
			}
			if(App.activeObject)
			{
				//id
				var srcEditImg = false;
				var objId = App.activeObject.attr('id');
				
				App.activeObject.children().each(function(){ 
						if($(this).attr('id') == "img"+App.activeObject.attr('id')){ 
							srcEditImg = $(this).attr('id');
						}
				});
				
				//object type
				var typeObj = App.activeObject.attr('object_type');
				
				//width
				var subStrWidth = App.activeObject.css('width');
				var toRemoveWdt = 'px';
				var newWidthPlus = subStrWidth.replace(toRemoveWdt, '');
				
				//height
				var subStrHgh = App.activeObject.css('height');
				var toRemoveHgh = 'px';
				var newHeightPlus = subStrHgh.replace(toRemoveHgh, '');
				
				//top
				var subStrTop = App.activeObject.css('top');
				var toRemoveTop = 'px';
				var newTopPlus = subStrTop.replace(toRemoveTop, '');
				
				//left
				var subStrLeft = App.activeObject.css('left');
				var toRemoveLeft = 'px';
				var newLeftPlus = subStrLeft.replace(toRemoveLeft, '');
				
				if(typeObj == "chart")
				{	 
					//Check if tools is not opened
					if(App.chartToolbox.isOpen == 0)
					{
						
						App.chartToolbox.editClick = true;
						
						var listValue = App.activeObject.attr('chart-data');
						App.chartToolbox.charData = listValue.split(',');
						
						App.heightChartDraw = parseInt(newWidthPlus); 
						App.widthChartDraw = parseInt(newHeightPlus);

						App.chartToolbox.imgIdTemp = App.activeObject.attr('id');
						var listValue = App.activeObject.attr('chart-data'); 
						 
						if(App.activeObject.attr('scale') == '1'){ 
							$("#y-axis").attr("checked","checked");
						}else{
							$("#x-axis").attr("checked","checked");
						}
						
						// App.updateChartProperty(App.chartToolbox.charData,App.chartToolbox.radioChartVal, App.lastClickPoint.x,App.lastClickPoint.y,App.chartToolbox.widthChart, App.chartToolbox.heightChart);
						
						// var allData = {
					// "file_id": App.fileId,
					// "page_id":App.pageId,
					// "id": App.chartToolbox.imgIdTemp,
					// "posx":posx,
					// "posy":posy,
					// "type_chart" : typeChart,
					// "data_chart" : dataChart,
					// "width_chart" : parseInt(wChart),
					// "height_chart" : parseInt(hChart),
					// "axisCrd" : parseInt(App.chartToolbox.scale90),
					// "fill_color" : App.chartToolbox.fillColor,
					// "gradient" : App.chartToolbox.gradient,
					// "start_color" : App.chartToolbox.startColor,
					// "end_color" : App.chartToolbox.endColor,
					// "username":App.username,
					// "curr_date":strDate 
							
						App.chartToolbox.imgIdTemp = App.activeObject.attr('id');
						App.chartToolbox.scale90 = App.activeObject.attr('scale');
						// App.chartToolbox.fillColor = App.activeObject.attr('scale');
						// App.chartToolbox.startColor = App.activeObject.attr('scale');
						// App.chartToolbox.startColor = App.activeObject.attr('scale');
						App.chartToolbox.radioChartVal = App.activeObject.attr('type_chart');
					
						App.chartToolbox.widthChart = App.activeObject.attr('width');
						App.chartToolbox.heightChart = App.activeObject.attr('height');
						// App.updateChartProperty(App.chartToolbox.charData,App.activeObject.attr('type_chart'), App.activeObject.css('left'),App.activeObject.css('top'),App.activeObject.css('width'), App.activeObject.css('height'));
						if(App.activeObject.attr('type_chart') == "bar"){
							// alert("bar");
							$('#bar-start').css('display','block');
							$('#pie-start').css('display','none');	
							$('#pie-chart-start').css('display','none');
							$('#grad-bar').css('display','block');					
							$('#color-grad').css('display','block');
							$('#bar').attr('checked','checked');
							$('#bar-choose').attr('checked','checked');
							$('#3D-choose').removeAttr('checked');
							if(App.activeObject.attr('gradient')  == "0"){
								$('#gradient').removeAttr('checked');
							}else{
								$('#gradient').attr('checked','checked');
							} 
						}else if(App.activeObject.attr('type_chart') == "line"){
							// alert("bar");
							$('#bar-start').css('display','block');
							$('#pie-start').css('display','none');	
							$('#pie-chart-start').css('display','none');
							$('#grad-bar').css('display','none');					
							$('#color-grad').css('display','none'); 
							$('#bar').attr('checked','checked');
							$('#line-choose').attr('checked','checked');
							$('#3D-choose').removeAttr('checked');
							$('#gradient').removeAttr('checked');
						}else if(App.activeObject.attr('type_chart') == "acc"){
							// alert("acc");
							$('#bar-start').css('display','none'); 
							$('#pie-start').css('display','none'); 
							$('#pie-chart-start').css('display','none');
							$('#grad-bar').css('display','none');					
							$('#color-grad').css('display','none'); 
							$('#acc').attr('checked','checked');
							$('#3D-choose').removeAttr('checked');
							$('#gradient').removeAttr('checked');
						}else if(App.activeObject.attr('type_chart') == "pie"){
							$('#pie-start').css('display','block'); 
							$('#bar-start').css('display','none'); 
							$('#pie-chart-start').css('display','block'); 
							$('#grad-bar').css('display','none');					
							$('#color-grad').css('display','none'); 
							$('#pie').attr('checked','checked');
							$('#pie-choose').attr('checked','checked');
							$('#gradient').removeAttr('checked');
							$('#3D-choose').removeAttr('checked');
						}else if(App.activeObject.attr('type_chart') == "ring"){
							$('#pie-start').css('display','none'); 
							$('#bar-start').css('display','none'); 
							$('#pie-chart-start').css('display','block'); 
							$('#grad-bar').css('display','none');					
							$('#color-grad').css('display','none'); 
							// $('#3D-choose').css('display','none'); 
							$('#pie').attr('checked','checked');
							$('#ring-choose').attr('checked','checked');
							$('#3D-choose').removeAttr('checked');
							$('#gradient').removeAttr('checked');
						}else if(App.activeObject.attr('type_chart') == "3Dpie"){
							$('#pie-start').css('display','block'); 
							$('#bar-start').css('display','none'); 
							$('#pie-chart-start').css('display','block'); 
							$('#grad-bar').css('display','none');					
							$('#color-grad').css('display','none'); 
							$('#pie').attr('checked','checked');
							$('#pie-choose').attr('checked','checked');
							$('#3D-choose').attr('checked','checked');
							$('#gradient').removeAttr('checked');
						}
						// App.chartToolbox.gradient = $('#gradient').val(); 
						var sizeChartData = App.chartToolbox.charData.length;
						//console.log(sizeChartData);
						var newListValue = false;
						//console.log($('#list-value').val());
						for(var i = 0; i < sizeChartData; i++)
						{ 						
							newListValue = $('<div></div>').attr({'id':i,'class':'chart-point-box'}).html(App.chartToolbox.charData[i]).appendTo($('#list-value'));
							newListValue.click(function(e) { 
								indxList = e.currentTarget.id;
								//console.log(indxList); 
								if(App.chartToolbox.selectedList){
									App.chartToolbox.selectedList.attr('class', 'chart-point-box');
								}						
								$(this).attr('class', 'chart-point-box-selected');
								App.chartToolbox.selectedList=$(this);
							});
						}
						 var color1 = App.activeObject.attr('color1');
						 var color2 = App.activeObject.attr('color2');
						 var color3 = App.activeObject.attr('color3');
						for(var i=0;i<$.jPicker.List.length;i++)
						{
							if($.jPicker.List[i].id == "colorChart")
							{
								if(color1)
									$.jPicker.List[i].color.active.val('hex', color1, this);
								else
									$.jPicker.List[i].color.active.val('hex', "ffcc00", this);
							}
							else if($.jPicker.List[i].id == "startColorChart")
							{
								if(color2){
									$.jPicker.List[i].color.active.val('hex', color2, this);
									App.chartToolbox.startColor = color2;
								}
								else
									$.jPicker.List[i].color.active.val('hex', "ffcc00", this);
							}
							else if($.jPicker.List[i].id == "endColorChart")
							{
								if(color3){
									$.jPicker.List[i].color.active.val('hex', color3, this);
									App.chartToolbox.endColor = color3;
								}
								else
									$.jPicker.List[i].color.active.val('hex', "ffcc00", this);
							}
						}
						App.openedTool= $(".chart-tools");
							App.openedTool.addClass('active');
						 App.chartToolbox.show(); 
					}else{
						alert(App.localize("%tool_open_already"));
					}
				}
				if(typeObj == "image"){
					App.openedTool = $('#tool_shape_ico'); 
					App.openedTool.addClass('active');
					App.editProp.x = parseInt(App.activeObject.offset().left);
					App.editProp.y = parseInt(App.activeObject.offset().top);
					App.editProp.width = parseInt(App.activeObject.width());
					App.editProp.height = parseInt(App.activeObject.height());
					App.editProp.bgCanvas = App.activeObject.children(":first").attr('src');

					App.toolbox.showForEdit(objId);
				}
				
				if(typeObj == "text"  || typeObj == "buble" || typeObj == "sticky-text"){ 
				
					if(typeObj == "text")
						App.openedTool = $('#tool_text_ico');
					else if(typeObj == "sticky-text")
						App.openedTool = $('#sticky-text-tools'); 
					else
						App.openedTool = $('#tool_text_bubble_ico'); 
					App.openedTool.addClass('active');
					App.richText.enterEditMode(objId);
				}
				
				// if(typeObj == "sticky-text"){ 
					// App.openedTool = $('#sticky-text-tools'); 
					// App.openedTool.addClass('active');
					// App.stickyText.enterEditMode(objId);
				// }
				
				if(typeObj == "table"){ 
				
					App.openedTool = $('#tool_table_ico'); 
					App.openedTool.addClass('active');
					
					$(this).addClass('active');
					App.openedTool = $(this);
					$("#value-row").val($('#tbl_'+objId+' tr').length);
					$("#value-column").val($('#tbl_'+objId+' tr:first td').length);
					var strBorder = $('#'+objId).attr("border_style");
					var strWidth = strBorder.substr(0,strBorder.indexOf("px"));
					
					$('#width_'+strWidth).css("background-color", "rgb(255, 105, 180)");
					
					var strSubStyle = strBorder.substr(strBorder.indexOf(" ")+1); 
					strSubStyle = strSubStyle.substr(0,strSubStyle.indexOf(" "));  
					strSubStyle = $('#'+objId).attr("bd-style");
					
					$('.width_list').css('background-color','');
					$('.style_list').css('background-color','');
					
					if(strSubStyle == "solid"){
						$('#style_1').css("background-color", "rgb(255, 105, 180)");
					}else if(strSubStyle == "dashed"){
						$('#style_2').css("background-color", "rgb(255, 105, 180)");
					}else if(strSubStyle == "dotted"){
						$('#style_3').css("background-color", "rgb(255, 105, 180)");
					}
					
					
					var thickness =  $('#'+objId).attr("thickness");
					if(thickness == "1px"){
						$('#width_1').css("background-color", "rgb(255, 105, 180)");
					}
					else if(thickness == "2px"){
						$('#width_2').css("background-color", "rgb(255, 105, 180)");
					}
					else if(thickness == "4px"){
						$('#width_3').css("background-color", "rgb(255, 105, 180)");
					}
					else if(thickness == "8px"){
						$('#width_4').css("background-color", "rgb(255, 105, 180)");
					}
					else if(thickness == "16px"){
						$('#width_5').css("background-color", "rgb(255, 105, 180)");
					}
					
					App.initialTableToolbox.widthChoose = thickness;
					App.initialTableToolbox.styleChoose = strSubStyle;
					var strSubRGB = strBorder.substr(strBorder.indexOf(" ")+1); 
					strSubRGB = strSubRGB.substr(strSubRGB.indexOf(" ")+1); 
					strSubRGB = App.Util.colorToHex(strSubRGB);
					for(var i=0;i<$.jPicker.List.length;i++)
					{
						if($.jPicker.List[i].id == "label-color-table")
						{
							$.jPicker.List[i].color.active.val('hex', strSubRGB, this);
							break;
						}
					}
					App.initialTableToolbox.show();
					App.isTableEdit = 1;
					App.initialTableToolbox.widthTableLast = newWidthPlus;
					App.initialTableToolbox.heightTableLast = newHeightPlus;
					App.lastIdTable = objId;
					App.initialTableToolbox.leftTableLast = newLeftPlus;
					App.initialTableToolbox.topTableLast = newTopPlus; 
					App.initialTableToolbox.isEditClick = 1;
				}
				
			}
			
			
		},
		
		
		updateChartProperty:function(dataChart,typeChart,posx,posy, wChart, hChart){ 
			var d = new Date();
			var strDate = d.getDate() + "/" + (d.getMonth()+1) + "/" + d.getFullYear(); 
			var url = App.baseUrl+"CommHub/update_chart_property/";
			var allData = {
					"file_id": App.fileId,
					"page_id":App.pageId,
					"id": App.chartToolbox.imgIdTemp,
					"posx":posx,
					"posy":posy,
					"type_chart" : typeChart,
					"data_chart" : dataChart,
					"width_chart" : parseInt(wChart),
					"height_chart" : parseInt(hChart),
					"axisCrd" : parseInt(App.chartToolbox.scale90),
					"fill_color" : App.chartToolbox.fillColor,
					"gradient" : App.chartToolbox.gradient,
					"start_color" : App.chartToolbox.startColor,
					"end_color" : App.chartToolbox.endColor,
					"username":App.username,
					"curr_date":strDate
			};
								
			var request =$.ajax({
					type: 'POST',
					url: url,
					data:allData
				});
				request.done(function(msg) {
					var parsedObject = JSON.parse(msg);
					
					App.currentStackIndex++;
					App.actionStack[App.currentStackIndex] = parsedObject.history;
					parsedObject = JSON.parse(parsedObject.message);
					//console.log(parsedObject);
					var idDiv = parsedObject.id;
					$('#'+idDiv).remove();
					App.socket.emit('cm_delete', {roomid: App.fileId, deletedId: idDiv, id: App.userId,type:"object" }); 
					App.loadChartObject(parsedObject);  
					App.socket.emit('cm_new', {roomid: App.fileId,pageid:App.pageId,  object:parsedObject, id: App.userId,objId:$(this).attr('id'),type:'chart' });  
				});
				request.fail(function(jqXHR, textStatus) {
				});
				request.always(function(){
				});
		},
		
		updateTableProperty:function(rowTable,colTable,posx,posy){  
			var d = new Date();
			var strDate = d.getDate() + "/" + (d.getMonth()+1) + "/" + d.getFullYear(); 
			
			var tblId = (new Date).getTime(); 
			var url = App.baseUrl+"CommHub/update_table/";
			var colorRGB = "rgb("+App.initialTableToolbox.rColor+","+App.initialTableToolbox.gColor+","+App.initialTableToolbox.bColor+")";
			var borderStyle = App.initialTableToolbox.widthChoose+" "+App.initialTableToolbox.styleChoose+" "+colorRGB; 
			mytable = $('<table></table>').attr({ id: "tbl_"+tblId, border:"2px"}); 
			var tr = [];
			var htmlString="";
			for (var i = 0; i < rowTable; i++) {
				htmlString+='<tr style="border:'+borderStyle+';">';
				var row = $('<tr></tr>').attr({ class: ["class1"].join('') }).css("border", borderStyle).appendTo(mytable);
				for (var j = 0; j < colTable; j++) {
					htmlString+='<td style="border:'+borderStyle+';"></td>';
				}
				htmlString += "</tr>";
			}
			mytable.html(htmlString);
			var allData = {
					"file_id":App.fileId,
					"page_id":App.pageId,
					"id": App.lastIdTable,  
					"width":App.initialTableToolbox.widthTableLast,
					"height":App.initialTableToolbox.heightTableLast,
					"posx":posx,
					"posy":posy,
					"content_table":mytable.html(),
					"username":App.username,
					"curr_date":strDate,
					"border_style":borderStyle,
					"style":App.initialTableToolbox.styleChoose,
					"thickness":App.initialTableToolbox.widthChoose,
					"row_table":rowTable,
					"col_table":colTable
			};
			var request =$.ajax({
				type: 'POST',
				url: url,
				data:allData
			});
			request.done(function(msg) {  
				var parsedObject = JSON.parse(msg);
				App.currentStackIndex++;
				App.actionStack[App.currentStackIndex] = parsedObject.history;
				parsedObject = JSON.parse(parsedObject.message);
				var idTable = parsedObject.id; 
				$('#'+idTable).remove();  
				App.socket.emit('cm_delete', {roomid: App.fileId, deletedId: idTable, id: App.userId,type:"object" }); 
				App.loadTableObject(parsedObject);  
				App.socket.emit('cm_new', {roomid: App.fileId,pageid:App.pageId,  object:parsedObject, id: App.userId,objId:$(this).attr('id'),type:'table' }); 
			});
			request.fail(function(jqXHR, textStatus) {
			});
			request.always(function(){
			});
		},
							
	
		
		newPageLayers:function(size){
			var url = App.baseUrl+"CommHub/add_page_object/";
			var allData = {
					"file_id": App.fileId,
					"width" : size.width,
					"height" : size.height 
			}; 
								
			var request =$.ajax({
					type: 'POST',
					url: url,
					data:allData
				});
				request.done(function(msg) {
					var parsedObject = JSON.parse(msg);
					App.loadPageObject(parsedObject);
					App.socket.emit('cm_new_page', {
						roomid: App.fileId,
						pageid:App.pageId,  
						object:parsedObject, 
						id: App.userId,objId:$(this).attr('id')
						}); 
					App.pageCount++;
					App.updateFileTitle();
				});
				request.fail(function(jqXHR, textStatus) {
					//alert("Failed to add layer");
				});
				request.always(function(){
					//alert("Create layer failed due to several reason, please try again later");
				});
		},
		
		newFilePageLayers:function(valFileName,groupId){
			
			var url = App.baseUrl+"CommHub/add_file_page_object/";
			var file_paper_size = App.pageFile.getPaperSize($("#page-selector").val());
			var allData = {
					"file_id": App.fileId, 
					"file_name": valFileName, 
					"width": file_paper_size.width, 
					"height": file_paper_size.height, 
					"group_id": groupId, 
			}; 
				
			var request =$.ajax({
					type: 'POST',
					url: url,
					data:allData
				});
				request.done(function(msg) {
					// //console.log(msg); 
					window.location.href = App.baseUrl+"home/draw?f_id="+msg;
					App.fileId = msg;
					App.pageId = 1;
				});
				request.fail(function(jqXHR, textStatus) {
				});
				request.always(function(){
				});
		},
						
		// colorPickerSelected:function(){
			// $('.jPicker').jPicker(
			// {
			  // window:
			  // {
				// expandable: true
			  // }
			// });
		// },
		
		htmlToImage:function(currPageId){ 
			html2canvas(document.getElementsByClassName('drawContainer')[0], {
				//logging: true,
				width : 2200,
				height : 1200,
				onrendered: function(canvas) {
					if(App.updatingThumbnail)
						return;
						
					//alert("1");
					var dataImg = Canvas2Image.convertToPNG(canvas, 80, 60);
					//alert("2");
					//console.log(dataImg);
					var dataURL = dataImg.src;//$(dataImg).attr("src");
					//alert("3");
					var newImagePath = "documents/"+App.fileId+"/thumb-"+currPageId+".png";
					//alert(newImagePath);
					var url = App.baseUrl+"CommHub/add_thumb_canvas";
					var allData = {"file_id": App.fileId,
									"page_id": currPageId,
									"filepath" : newImagePath,
									"image_data": dataURL
								};
					var request = $.ajax({ //get data awal
									url: url,
									type: "POST",
									data: allData,
								});
					
					request.done(function(msg) { 
						var existingObject=false;	//check if it's an existing object
							for(var i =0;i<App.pages.length;i++)
							{
								var timeStamped = App.baseUrl+"documents/"+App.fileId+"/thumb-"+App.pages[i].attr('page-id')+".png?ts="+(new Date).getTime();
								var imageElement = App.pages[i].children();
								imageElement.attr('src',timeStamped);
							}
							
					});
					request.fail(function(jqXHR, textStatus) { 
					});
					request.always(function(){
					});
				}
			});
		},
				
		addTableToServer:function(rowTable,colTable,posx,posy){
			var d = new Date();
			var strDate = d.getDate() + "/" + (d.getMonth()+1) + "/" + d.getFullYear(); 
		
			var tblId = (new Date).getTime();  
			
			var url = App.baseUrl+"CommHub/add_table/";
			if(App.initialTableToolbox.widthChoose == false){
				App.initialTableToolbox.widthChoose = "1px";
			}
			if(App.initialTableToolbox.styleChoose == false){
				App.initialTableToolbox.styleChoose = "solid";
			}
			var colorRGB = "rgb("+App.initialTableToolbox.rColor+","+App.initialTableToolbox.gColor+","+App.initialTableToolbox.bColor+")";
			var borderStyle = App.initialTableToolbox.widthChoose+" "+App.initialTableToolbox.styleChoose+" "+colorRGB;
			 
			$('.td-table').css("border", borderStyle);
			mytable = $('<table></table>').attr({ id: "tbl_"+tblId, border:"2px"}); 
			var tr = [];
			var htmlString="";
			for (var i = 0; i < rowTable; i++) {
				htmlString+='<tr style="border:'+borderStyle+';">';
				var row = $('<tr></tr>').attr({ class: ["class1"].join('') }).css("border", borderStyle).appendTo(mytable);
				for (var j = 0; j < colTable; j++) {
					htmlString+='<td style="border:'+borderStyle+';"></td>';
				}
				htmlString += "</tr>";
			}
			mytable.html(htmlString);
			
			//console.log(mytable.html());
			var allData = {
					"file_id":App.fileId,
					"page_id":App.pageId,
					"id": tblId,  
					"width":550,
					"height":374,
					"posx":posx,
					"posy":posy,
					"content_table":mytable.html(),
					"username":App.username,
					"curr_date":strDate,
					"border_style":borderStyle,
					"style":App.initialTableToolbox.styleChoose,
					"thickness":App.initialTableToolbox.widthChoose,
					"row_table":rowTable,
					"col_table":colTable
					

			};
			var request =$.ajax({
				type: 'POST',
				url: url,
				data:allData
			});
			request.done(function(msg) {  
				var parsedObject = JSON.parse(msg);
				
				App.currentStackIndex++;
				App.actionStack[App.currentStackIndex] = parsedObject.history;
				parsedObject = JSON.parse(parsedObject.message);
				App.loadTableObject(parsedObject);
				
				App.socket.emit('cm_new', {roomid: App.fileId,pageid:App.pageId,  object:parsedObject, id: App.userId,objId:$(this).attr('id'),type:parsedObject.type }); 
			});
			request.fail(function(jqXHR, textStatus) {
			});
			request.always(function(){
			});
		},
		
		saveAsFileObject:function(valFileName,asTemplate,groupId){
		
			var url = App.baseUrl+"CommHub/add_file_page_object/";
			var allData = {
					"file_id": App.fileId, 
					"file_name": valFileName, 
					"group_id": groupId, 
			}; 
								
			var request =$.ajax({
					type: 'POST',
					url: url,
					data:allData
				});
			 var isTemplate = 0;
			 if(asTemplate)
			 	isTemplate = 1;
			request.done(function(msg) {
				var newIdFile = msg;		
					var url = App.baseUrl+"CommHub/add_save_as";
					var allData = {"file_id_source":  App.fileId,
									"file_id_target":  newIdFile,
									"is_template" : isTemplate
									}
					
					var request = $.ajax({ //get data awal
						url: url,
						type: "POST",
						data: allData,
					});
					request.done(function(msg) {					
					});
					request.fail(function(jqXHR, textStatus) {
					});
					request.always(function(){
					});
			});
			request.fail(function(jqXHR, textStatus) {
			});
			request.always(function(){
			});
		},
		
		goToPreview:function(){
			var my_window = false;
			var url = App.baseUrl+"home/draw_preview?f_id="+App.fileId+"&page_id="+App.pageId;
			my_window = window.open(url);
		},
		
		zoomPlus:function(){
			var tempWindowHeightNew = $(window).height() + 88;
			var tempWindowWidthNEw = $(window).width() + 50;
			window.resizeTo(tempWindowWidthNEw,tempWindowHeightNew);
			 
			var newScale = (tempWindowWidthNEw/250)*0.18;
			var scaleStr = 'scale(' + newScale + ')'; 

			//width
				var subStrWidth = $('#areaPreview').css('width');
				var toRemoveWdt = 'px';
				var newWidthPlus = subStrWidth.replace(toRemoveWdt, '');
				var newWidthPlusInt = parseInt(newWidthPlus) + 20;
			//height
				var subStrHgh = $('#areaPreview').css('height');
				var toRemoveHgh = 'px';
				var newHeightPlus = subStrHgh.replace(toRemoveHgh, '');
				var newHeightPlusInt = parseInt(newHeightPlus) + 15;  
				
			$('#areaPreview').css('width', parseInt(newWidthPlusInt) );
			$('#areaPreview').css('height', parseInt(newHeightPlusInt));
			
			$('#areaPreview').children().each(function(){
				if($(this).attr('id') == "rootContainer")
				{ 
					$(this).css('transform',scaleStr); 
				} 
			}); 
			
		},
		
		zoomSmall:function(){

			if($(window).height() > 150){
				var tempWindowHeightNew = $(window).height() +58 ;
				var tempWindowWidthNEw = $(window).width() - 14;
				window.resizeTo(tempWindowWidthNEw,tempWindowHeightNew);
				 
				var newScale = (tempWindowWidthNEw/250)*0.18;
				var scaleStr = 'scale(' + newScale + ')'; 

				 
					var subStrWidth = $('#areaPreview').css('width');
					var toRemoveWdt = 'px';
					var newWidthPlus = subStrWidth.replace(toRemoveWdt, '');
					var newWidthPlusInt = parseInt(newWidthPlus) - 20;
				 
					var subStrHgh = $('#areaPreview').css('height');
					var toRemoveHgh = 'px';
					var newHeightPlus = subStrHgh.replace(toRemoveHgh, '');
					var newHeightPlusInt = parseInt(newHeightPlus) - 15;  
				
				$('#areaPreview').css('width', parseInt(newWidthPlusInt) );
				$('#areaPreview').css('height', parseInt(newHeightPlusInt));
				
				$('#areaPreview').children().each(function(){
					if($(this).attr('id') == "rootContainer")
					{ 
						$(this).css('transform',scaleStr); 
					} 
				}); 
			}
			
		},
		
		deleteFile:function(){
				// if(App.isModeArea == 1){
					var r=confirm(App.localize("%delete_workspace_confirmation"));
					if (r==true)
					{
						var url = App.baseUrl+"CommHub/delete_file_workspace/"; 
						var allData = {
								"file_id": App.fileId,
						}; 
						var request =$.ajax({
								type: 'POST',
								url: url,
								data:allData
						});

						request.done(function(msg) {  
							App.socket.emit('cm_delete', {roomid: App.fileId, deletedId: App.fileId, id: App.userId,type:"file" }); 
							window.location.replace(App.baseUrl+"home");
							
						});
						request.fail(function(jqXHR, textStatus) {
						});
						request.always(function(){
						});
					}	
				// }else{
					// alert(App.localize("%view_mode_warning_dialog"));
				// }	
		},
		openWorkspace:function(){
			var url = App.baseUrl+"CommHub/open_workspace/"; 
			
			var request =$.ajax({
					type: 'POST',
					url: url
					// data:allData
				});
			request.done(function(msg) {  
				var parsedObject = JSON.parse(msg);
				//console.log(parsedObject);
				//Nanda - Notes: check validation if files workspace is empty
				if(parsedObject != null)
				{
					$('#listFileWorkspace').empty().append(parsedObject);
					App.openFileToolbox.show();	
				}else{
					alert(App.localize("%empty_files_confirmation"));
				} 
			});
			request.fail(function(jqXHR, textStatus) {
			});
			request.always(function(){
			});
			
		},
		openWorkspaceTemplate:function(){
			var url = App.baseUrl+"CommHub/open_workspace_template/"; 
			
			var request =$.ajax({
					type: 'POST',
					url: url
					// data:allData
				});
			request.done(function(msg) {  
				var parsedObject = JSON.parse(msg);
				console.log(parsedObject);
				//Nanda - Notes: check validation if files workspace is empty
				if(parsedObject != null)
				{
					$('#listFileWorkspaceTemplate').empty().append(parsedObject);
					App.openFileTemplateToolbox.show();
				}else{
					alert(App.localize("%empty_files_confirmation"));
				}
			});
			request.fail(function(jqXHR, textStatus) {
			});
			request.always(function(){
			});
			
		}, 
		openPlayerWindow:function(){
			var win=window.open(App.baseUrl+"home/player?f_id="+App.fileId+"&p_id="+App.pageId, '_blank');
			win.focus();
		},
		
		textToImage:function(posxText,posyText,textInput,colorText1,colorText2,textBackground1,colorBackground2,colorShadow,checkTransChar,isBold,isItalic,isUnderline,fontStyle, fontSize,checkGradChar,checkGradBack,valGradChar,valGradBack, widthDiv, heightDiv, checkVert, chooseSad, chooseWidthShad){
			if(colorText1 == false){
				colorText1 = "black";
			}
			if(colorText2 == false){
				colorText2 = "black";
			}
			if(textBackground1 == false){
				textBackground1 = "white";
			}
			if(colorBackground2 == false){
				colorBackground2 = "white";
			}
			if(colorShadow == false){
				colorShadow = "blue";
			}  
			 
			//console.log(widthDiv);
			//console.log(heightDiv);
			
			
			var url = App.baseUrl+"CommHub/text_to_image/"; 
			// var url = App.baseUrl+"CommHub/test/"; 
			var imgId = (new Date).getTime();  
			var d = new Date();
			var strDate = d.getDate() + "/" + (d.getMonth()+1) + "/" + d.getFullYear(); 
			var newImagePath = "documents/"+App.fileId+"/"+imgId+".png";
			var allData = { 
							"file_id":App.fileId,
							"page_id":App.pageId,
							"id": imgId,   
							"posx":posxText,
							"posy":posyText, 
							"username":App.username,
							"curr_date":strDate,
							"text_input": textInput,
							"image_path":newImagePath,
							"colorText1":colorText1,
							"colorText2":colorText2,
							"textBackground1":textBackground1,
							"colorBackground2":colorBackground2,
							"colorShadow":colorShadow,		
							"checkTransChar":checkTransChar,
							"isBold":isBold,
							"isItalic":isItalic,
							"isUnderline":isUnderline,
							"fontStyle":fontStyle,
							"fontSize":fontSize,
							"checkGradChar":checkGradChar,
							"checkGradBack":checkGradBack,
							"valGradChar":valGradChar,
							"valGradBack":valGradBack,
							"widthDiv":widthDiv,
							"heightDiv":heightDiv,
							"checkVert":checkVert,
							"chooseSad":chooseSad,
							"chooseWidthShad":chooseWidthShad
						}; 
			var request =$.ajax({
					type: 'POST',
					url: url,
					data:allData
				});
			request.done(function(msg) {  
				var parsedObject = JSON.parse(msg);
				parsedObject = JSON.parse(parsedObject.message);
				App.loadDrawingObject(parsedObject);
	
				App.socket.emit('cm_new', {roomid: App.fileId,pageid:App.pageId, object:parsedObject, id: App.userId,objId:$(this).attr('id'),type:"image" }); 	 
			});
			request.fail(function(jqXHR, textStatus) {
			});
			request.always(function(){
			});
		},
		
		
		addResizeable:function(object){	
			object.resizable({
				
				resize: function(event, ui) 
				{  
					App.socket.emit('cm_update', {roomid: App.fileId, size: ui.size, coordinate: ui.position, id: App.userId,objId:$(this).attr('id') }); 
				},
				start: function( event, ui ) {
					if(App.isModeArea != 1)
						 return;
					
					if(App.openedTool)
						return;
						
					App.onDrag = true;
					if(App.activeObject){
						//Firman Notes - Surface : Flag for cancel click Event After Drag
						//alert(navigator.userAgent);
						if((navigator.userAgent.match(/Android/i)
							|| navigator.userAgent.match(/webOS/i)
							|| navigator.userAgent.match(/iPhone/i)
							|| navigator.userAgent.match(/iPad/i)
							|| navigator.userAgent.match(/iPod/i)
							|| navigator.userAgent.match(/BlackBerry/i)
							|| navigator.userAgent.match(/Touch/i)
							|| navigator.userAgent.match(/Windows Phone/i))){
							App.isSurface = true;
						}
					
					}
				},
				handles: {
						'se': '#segrip',
						'n': '#ngrip',
						'e': '#egrip',
						's': '#sgrip',
						'w': '#wgrip'
				},
				stop: function( event, ui ) 
				{
					var position = ui.position;
					var id = $(this).attr("id");
					var width = $(this).css("width").split(".")[0];
					var height = $(this).css("height").split(".")[0];
					var content =  $('#text_content_'+id).html(); 
					var objectJson = {"content":content,	"id": id, "posy": position.top, "posx": position.left, "height": parseInt(height), "width": parseInt(width) };
					var url = App.baseUrl+"CommHub/update_object_property";
					var newData = {"file_id": App.fileId,
									"page_id":App.pageId,
									"object_json":JSON.stringify(objectJson),
								}
							
					var req =$.ajax({
						type: 'POST',
						url: url,
						data:newData
					});
					req.done(function(msg){
						msg = JSON.parse(msg);
						App.currentStackIndex++;
						App.actionStack[App.currentStackIndex] = msg.history;
					});
					if((navigator.userAgent.match(/Android/i)
							|| navigator.userAgent.match(/webOS/i)
							|| navigator.userAgent.match(/iPhone/i)
							|| navigator.userAgent.match(/iPad/i)
							|| navigator.userAgent.match(/iPod/i)
							|| navigator.userAgent.match(/BlackBerry/i)
							|| navigator.userAgent.match(/Touch/i)
							|| navigator.userAgent.match(/Windows Phone/i))){
							App.isSurface = true;
						}
				}
			});
		},
		addDraggable:function(object){
			
			object.draggable(
			{
				containment: 'parent',
				drag: function( event, ui ) 
				{	
					if(App.openedTool)
						return false;
					if(App.isModeArea != 1)
						 return false;
					
					if(App.propertyToolbox.isGrid == 1){
						var tempTop = parseInt(ui.position.top)/App.propertyToolbox.heightGrid;//20;
						ui.position.top = parseInt(tempTop)*App.propertyToolbox.heightGrid;//20;
						var tempLeft = parseInt(ui.position.left)/App.propertyToolbox.heightGrid;//20;
						ui.position.left = parseInt(tempLeft)*App.propertyToolbox.heightGrid;//20;
					}
					App.socket.emit('cm_update', {roomid: App.fileId, coordinate: ui.position, id: App.userId,objId:$(this).attr('id') });
				},
				start: function( event, ui ) {
					if(App.isModeArea != 1)
						 return;
					
					if(App.openedTool)
						return;
					if(App.getLockStatus($(this).attr('id')))
					{
						
						var locker = App.getLockerUsername($(this).attr('id'));
						if(!locker)
							alert(App.localize("%locked_object_desc"));
						else
							alert(App.localize("%lock_edited")+locker);
						return;
					}	
					App.onDrag = true;
					if(App.activeObject){
						if(App.activeObject.attr('id') != $(this).attr('id')){
							App.switchActiveObject($(this));
							App.socket.emit('cm_select_object', {
										roomId: App.fileId, 
										pageId: App.pageId, 
										userId: App.userId,
										username: App.username,
										objectId:$(this).attr('id') 
							});
						
						}
						//Firman Notes - Surface : Flag for cancel click Event After Drag
						//alert(navigator.userAgent);
						if((navigator.userAgent.match(/Android/i)
							|| navigator.userAgent.match(/webOS/i)
							|| navigator.userAgent.match(/iPhone/i)
							|| navigator.userAgent.match(/iPad/i)
							|| navigator.userAgent.match(/iPod/i)
							|| navigator.userAgent.match(/BlackBerry/i)
							|| navigator.userAgent.match(/Touch/i)
							|| navigator.userAgent.match(/Windows Phone/i))){
							App.isSurface = true;
						}
					
					}
					else
					{
						App.switchActiveObject($(this));
						App.socket.emit('cm_select_object', {
									roomId: App.fileId, 
									pageId: App.pageId, 
									userId: App.userId,
									username: App.username,
									objectId:$(this).attr('id') 
						});
					}
				},
				stop: function( event, ui ) 
				{
					if(App.openedTool)
						return;
					if(App.isModeArea != 1)
						 return;
					
					App.onDrag = false;
					var position = ui.position;
					var id = $(this).attr("id");
					var width = $(this).css("width").split(".")[0];
					var height = $(this).css("height").split(".")[0];
			
					var content =  $('#text_content_'+id).html(); 
					var objectJson = {"content":content,"id": id, "posy": position.top, "posx": position.left, "height": parseInt(height), "width": parseInt(width) };
					//console.log(objectJson);
					var url = App.baseUrl+"CommHub/update_object_property";
					var newData = {
									"file_id": App.fileId,
									"page_id":App.pageId,
									"object_json":JSON.stringify(objectJson),
								  };
							
					var req = $.ajax({
						type: 'POST',
						url: url,
						data:newData
					});
					req.done(function(msg){
						msg = JSON.parse(msg);
						App.currentStackIndex++;
						App.actionStack[App.currentStackIndex] = msg.history;
						console.log(App.currentStackIndex);
						console.log(App.actionStack.length-App.currentStackIndex);
						App.actionStack.splice(App.currentStackIndex+1,App.actionStack.length-App.currentStackIndex);
						console.log(App.actionStack);
					});
					
					
				}
			});
		},
		disableDragResize:function(object){
			object.draggable('disable');
			object.resizable('disable');
			object.find("#"+object.attr('id')+"-c").attr("disabled", true);
			object.find("#segrip").attr("disabled", true);
			object.find("#ngrip").attr("disabled", true);
			object.find("#sgrip").attr("disabled", true);
			object.find("#egrip").attr("disabled", true);
			object.find("#wgrip").attr("disabled", true); 
		},
		
		addResizeHandlerImage:function(object,id){
			object.append('<div class="ui-resizable-handle ui-resizable-se resize-grip'+id+'" id="segrip"><img src="'+App.baseUrl+'assets/css/images/arrow_diagonal.png"></img></div>');
			object.append('<div class="ui-resizable-handle ui-resizable-n resize-grip'+id+'" id="ngrip"><img src="'+App.baseUrl+'assets/css/images/arrow_up.png"></img></div>');
			object.append('<div class="ui-resizable-handle ui-resizable-s resize-grip'+id+'" id="sgrip"><img src="'+App.baseUrl+'assets/css/images/arrow_down.png"></img></div>');
			object.append('<div class="ui-resizable-handle ui-resizable-e resize-grip'+id+'" id="egrip"><img src="'+App.baseUrl+'assets/css/images/arrow_side.png"></img></div>');
			object.append('<div class="ui-resizable-handle ui-resizable-w resize-grip'+id+'" id="wgrip"><img src="'+App.baseUrl+'assets/css/images/arrow_left.png"></img></div>');		
					
		},
		disableMobileContext:function(object){
			object.find("#context_ico_"+object.attr('id')).css("display", "none");
			object.find("#context_ico_"+object.attr('id')).attr("enabled","0");
		},
		addMobileContextImage:function(object,id){
			object.append('<div class="context_ico_'+id+'" id="context_ico_'+id+'"><img src="'+App.baseUrl+'assets/css/images/plus_signal.png"></img></div>');	
			$('#context_ico_'+id).css("width","20px");
			$('#context_ico_'+id).css("height","20px");
			$('#context_ico_'+id).css("position","absolute");
			$('#context_ico_'+id).css("top","0px");
			$('#context_ico_'+id).css("left","0px");
			object.find("#context_ico_"+object.attr('id')).attr("enabled","1");
			// $('#context_ico_'+id).on("touchstart",function(e){
				// var custParam={pageX:e.originalEvent .pageX,pageY:e.originalEvent .pageY};
				// object.trigger('contextmenu',custParam);
			// });
					
		},
		addCreatorNote:function(object,objectData){
			var createdContainer = $('<div></div>').attr({'id':objectData.id+"-c"}).appendTo(object);
			createdContainer.css("position","relative"); 
			createdContainer.css("text-align","center"); 
			createdContainer.css('border','1px solid #000000');
			createdContainer.css('width','120px');
			createdContainer.css('z-index','19');
			createdContainer.css('background-color',' #78C7C7');
			createdContainer.css('display','none');
			createdContainer.css('-webkit-border-radius','40px');
			createdContainer.css('-moz-border-radius','40px');
			createdContainer.css('border-radius','40px');
			createdContainer.addClass("user_note");
			createdContainer.attr("current_user","-1");
			var fontStr = $('<font></font>').attr({'size':'2', 'face':'comic sans ms'}).appendTo(createdContainer); 
			var strCreated = null;
			if(objectData.object_type == "attach"){
				var textAfter_ = objectData.content_file.substring(objectData.content_file.indexOf('_') + 1);
				strCreated = textAfter_+"<br>";
				createdContainer.css("word-wrap","break-word");
			}else{
				strCreated = "";
			} 
			if(objectData.created_by == null || objectData.created_date == null)
			{
				if(objectData.created_by == null && objectData.created_date == null){
					strCreated = strCreated+"unknown" + "<br>" + "unknown"; 
				}else if(objectData.created_by == null){
					strCreated = strCreated+"unknown" + "<br>" + objectData.created_date; 
				}else if(objectData.created_date == null){
					strCreated = strCreated+objectData.created_by + "<br>" + "unknown"; 
				}
			}else{
				strCreated = strCreated+objectData.created_by + "<br>" + objectData.created_date; 
			}
			fontStr.append(strCreated);
		},
		setupObjectEvent:function(object,data){
			if((data.object_type == "buble" || data.object_type == "text"|| data.object_type == "sticky-text" ))
			{
				object.on('dblclick',function(){ 
					if(data.isTemplate)
						return false;
					if(App.openedTool)
						return false;
					if(App.isModeArea != 1)
						 return false;
					if(App.richText.menu.isShow && (data.object_type == "buble" || data.object_type == "text" ))
						return;
					if(App.stickyText.menu.isShow && data.object_type == "sticky-text")
						return;
					if(!App.getLockStatus($(this).attr('id')) && App.isModeArea == 1)
					{
						App.switchActiveObject($(this));
						App.editObject();
					}
					else
					{
						
						var locker = App.getLockerUsername($(this).attr('id'));
						if(!locker)
							alert(App.localize("%locked_object_desc"));
						else
							alert(App.localize("%lock_edited")+locker);
					}
				});
			}
			
			
			//Long Press to show Context Menu
			/*
			var timeoutLongTouch;
			var $mydiv = object;

			// Listen to mousedown event
			$mydiv.on('mousedown.LongTouch', function (e) {
				
				$mydiv.trigger('click');
				timeoutLongTouch = setTimeout(function () {
					if(!App.onDrag){
						var custParam={pageX:e.pageX,pageY:e.pageY};	
						$mydiv.trigger('contextmenu',custParam);
					}
				}, 1000);
			})
			// Listen to mouseup event
			.on('mouseup.LongTouch', function () {
				// Prevent long touch 
				clearTimeout(timeoutLongTouch);
			});
			*/
			
			//Standard Behaviour
			object.on('mouseup',function(e){
				if(App.isSurface){
					App.isSurface = false;
					return;
				}
				
				
				if(App.openedTool)
				{
					return;
				}
				
				if(App.richText.menu.isShow && (data.object_type == "buble" || data.object_type == "text" ))
					return;
					
				if(App.stickyText.menu.isShow && data.object_type == "sticky-text")
					return;
					
				if(App.isModeArea != 1)
					 return;
					 
				if(App.getLockStatus(object.attr("id")) == App.lockEnum.ALL){
					if((navigator.userAgent.match(/Android/i)
						|| navigator.userAgent.match(/webOS/i)
						|| navigator.userAgent.match(/iPhone/i)
						|| navigator.userAgent.match(/iPad/i)
						|| navigator.userAgent.match(/iPod/i)
						|| navigator.userAgent.match(/BlackBerry/i)
						|| navigator.userAgent.match(/Touch/i)
						|| navigator.userAgent.match(/Windows Phone/i))){
						App.activeObjectReserve = object;
						var custParam={pageX:e.pageX,pageY:e.pageY};
						$(this).trigger('contextmenu',custParam);
						return;
					}
				}
				if(App.getLockStatus(object.attr("id")))
				{
					
						var locker = App.getLockerUsername(object.attr('id'));
						if(!locker)
							alert(App.localize("%locked_object_desc"));
						else
							alert(App.localize("%lock_edited")+locker);
					return;
				}	
				if(App.activeObject)
				{
					if(!(App.richText.menu.isEditMode && (data.object_type == "buble" || data.object_type == "text" || data.object_type == "sticky-text")) &&
						(navigator.userAgent.match(/Android/i)
						|| navigator.userAgent.match(/webOS/i)
						|| navigator.userAgent.match(/iPhone/i)
						|| navigator.userAgent.match(/iPad/i)
						|| navigator.userAgent.match(/iPod/i)
						|| navigator.userAgent.match(/BlackBerry/i)
						|| navigator.userAgent.match(/Touch/i)
						|| navigator.userAgent.match(/Windows Phone/i)))
					{
							if(App.activeObject.attr('id') == $(this).attr('id'))
							{
								var custParam={pageX:e.pageX,pageY:e.pageY};
								$(this).trigger('contextmenu',custParam);
							}	
					}
					
					var oldActiveWidth = App.activeObject.width();
					var oldActiveHeight = App.activeObject.height();
					if(data.object_type != "buble")
						App.activeObject.css('border','0px dashed #000000');
					if(!App.inBackLayer(App.activeObject))
					App.activeObject.css('z-index','18'); 
					
					$(".resize-grip"+App.activeObject.attr("id")).hide();
					
					App.toggleMobileMenuVisibility(App.activeObject.attr('id'),false);
					if(App.idIndicatorLast != null || App.idIndicatorLast != 0){
						$(".resize-grip"+App.idIndicatorLast).hide();
						App.toggleMobileMenuVisibility(App.idIndicatorLast,false);
						$("#"+App.idIndicatorLast+"-c").hide(); 
					}
					
					App.activeObject.width(oldActiveWidth);
					App.activeObject.height(oldActiveHeight);
					App.socket.emit('cm_unlock', {
						roomid: App.fileId,
						pageid:App.pageId,
						status:App.lockEnum.SELECT,
						objectId: App.activeObject.attr('id'), 
						id: App.userId,
						password:"", 
						without_pass:App.withoutPass
					});
					App.socket.emit('cm_deselect_object', {
							roomId: App.fileId, 
							pageId: App.pageId, 
							userId: App.userId,
							username: App.username,
							objectId:App.activeObject.attr('id') 
					});
					
					//ulum
					//console.log('cm_z_index');
					App.socket.emit('cm_z_index', {
							roomId: App.fileId, 
							pageId: App.pageId, 
							userId: App.userId,
							//username: App.username,
							objectId:App.activeObject.attr('id'),
							z_index:18
					});
				}
				
				App.socket.emit('cm_z_index', {
					roomId: App.fileId, 
					pageId: App.pageId, 
					userId: App.userId,
					objectId:$(this).attr("id"),
					z_index:19
				});
				
				$(".resize-grip"+$(this).attr("id")).show();
				App.toggleMobileMenuVisibility($(this).attr("id"),true);
				App.idIndicatorLast = $(this).attr("id");
				App.justSelectAnObject=true;
				
				App.activeObject=$(this);
				if(data.object_type == "text")
					App.activeObject.css('border','1px dashed #000000');
					
				if(!App.inBackLayer(App.activeObject))
				App.activeObject.css('z-index','20');
					
				
				
				App.socket.emit('cm_select_object', {
					roomId: App.fileId, 
					pageId: App.pageId, 
					userId: App.userId,
					username: App.username,
					objectId:$(this).attr('id') 
				});

				App.socket.emit('cm_lock', {
					roomid: App.fileId,
					pageid:App.pageId, 
					objectId: $(this).attr('id') , 
					id: App.userId,
					status:App.lockEnum.SELECT, 
					userName: App.username, 
					password:"", 
					without_pass:App.withoutPass
				});
				
				
					e.preventDefault(); //Firman Notes - Touch : Cancel Draggable For display context Menu
			
			});
			
			
			if(typeof data.isTemplate == 'undefined')//not a template object
			{ 
					App.addResizeHandlerImage(object,data.id);		
					// App.addMobileContextImage(object,data.id);
					if( !(navigator.userAgent.match(/Android/i)
						|| navigator.userAgent.match(/webOS/i)
						|| navigator.userAgent.match(/iPhone/i)
						|| navigator.userAgent.match(/iPad/i)
						|| navigator.userAgent.match(/iPod/i)
						|| navigator.userAgent.match(/BlackBerry/i)
						|| navigator.userAgent.match(/Touch/i)
						|| navigator.userAgent.match(/Windows Phone/i)))
					{
						App.disableMobileContext(object);
					}					
					App.addResizeable(object);
					App.addDraggable(object);	
					object.contextmenu(option);
					if(App.isModeArea != 1){
						App.disableDragResize(object);	
					}
			}
			else//a template,disable most of the menus
			{
				object.contextmenu(option);
				object.attr("is-template",1);
			} 
			$(".resize-grip"+data.id).hide();
			App.toggleMobileMenuVisibility(data.id,false);
		},
		goHome:function(){
			//Nanda - Notes: Add confirmation to return home 24072013
			var r=confirm(App.localize("%rtn_home_confirmation"));
			if (r==true)
			{
				if(App.activeObject)
				{				
					App.socket.emit('cm_unlock', {roomid: App.fileId,pageid:App.pageId, objectId: App.activeObject.attr("id"), id: App.userId,type:"object", status:0, userName: App.username, dateCreate: App.activeObject.attr("created_date")});
					
				} 
				App.socket.emit('cm_update_user_data', {
						username:App.username,
						user_id:App.userId,
						roomid:App.fileId, 
				});
				$("#overlay").show();
				// Nanda - Notes: When back to home (old=timeout 10s, new=timeout 3s)
				setTimeout(function(){
						$("#overlay").hide();
						window.location = App.baseUrl+"home/";
				}, 1500);
				
			}
			
		},
		setImageAsBackground:function(){
			if(App.activeObject)
			{
				//console.log(App.activeObject);
				if(App.activeObject.attr("object_type") == "image")
				{
					var objectId = App.activeObject.attr("id");
					var imageUrl = $('#img'+objectId).attr("src");
					//console.log(objectId);
					//console.log(imageUrl);
					$('#rootContainer').css('background-image', 'url(' + imageUrl + ')');
					$('#rootContainer').css('background-size', '100%');
					var url = App.baseUrl+"CommHub/set_page_background/";
					imageUrl = imageUrl.split("documents");
					imageUrl = "documents"+imageUrl[1];
					var allData = {
							"file_id": App.fileId, 
							"page_id": App.pageId, 
							"image_path": imageUrl, 
					}; 
										
					var request =$.ajax({
							type: 'POST',
							url: url,
							data:allData
						});
					request.done(function(msg) {
						App.socket.emit('cm_background', {
												roomId: App.fileId, 
												pageId:App.pageId, 
												imageUrl:imageUrl, 
												id: App.userId
											}); 
						
							App.propertyToolbox.heightGrid=0;
							App.propertyToolbox.isGrid=0;
							App.propertyToolbox.isDashed=0;
						
					});
					request.fail(function(jqXHR, textStatus) {
					});
					request.always(function(){
					});
				}
				else
				{
					alert(App.localize("%only_image_warning"));
				}
			}
		},
		clearBackground:function(){
			var url = App.baseUrl+"CommHub/set_page_background/";
					$('#rootContainer').css('background-image', 'url(' + App.baseUrl+  'documents/background-blank.png)');
					$('#rootContainer').css('background-size', '100%');
			var allData = {
					"file_id": App.fileId, 
					"page_id": App.pageId, 
					"image_path": "", 
			}; 
								
			var request =$.ajax({
					type: 'POST',
					url: url,
					data:allData
				});
			request.done(function(msg) {
				App.socket.emit('cm_background', {
					roomId: App.fileId, 
					pageId:App.pageId, 
					imageUrl:"", 
					id: App.userId
				}); 
				
				App.propertyToolbox.heightGrid=0;
				App.propertyToolbox.isGrid=0;
				App.propertyToolbox.isDashed=0;
				
			});
			request.fail(function(jqXHR, textStatus) {
			});
			request.always(function(){
			});
		},
		lockObject:function(typeLock){
			if(typeLock == "2prevMov"){
				if($('#'+App.idIndicatorLast).attr('is-template') != 1)
				{ 
					App.statusLock = App.lockEnum.MOVEMENT;
					
					App.lockObjectToolbox.show();
				} 
			}else if(typeLock == "2avPut"){
				if($('#'+App.idIndicatorLast).attr('is-template') != 1)
				{ 
					App.statusLock = App.lockEnum.EDIT;
					App.lockObjectToolbox.show();
					
				} 
			}else if(typeLock == "2notTouch"){
				$(".resize-grip"+$('#'+App.idIndicatorLast).attr("id")).hide();
				$("#"+App.idIndicatorLast+"_c").hide();
				
				App.statusLock = App.lockEnum.ALL;
				$(".without-lock-button").trigger('click');
				// App.lockObjectToolbox.show();
				
			}
		},
		
		unlockObject:function(){ 
			var isWithPass = false;
			var lockType=0;
			var i=0;
			if(!App.activeObject)
				App.activeObject = App.activeObjectReserve;
			for(i=0;i<App.lockedObjectList.lockedObject.length;i++)
			{  
				if(App.lockedObjectList.lockedObject[i].objectId == App.activeObject.attr('id') && App.lockedObjectList.lockedObject[i].password != "")
				{
					isWithPass = true;
					lockType= App.lockedObjectList.lockedObject[i].lock_status;
					break;
				} 
			}
			if(!isWithPass)
			{
				//alert("2");
				App.socket.emit('cm_unlock', {
							roomid: App.fileId,
							pageid:App.pageId,
							status:lockType,
							objectId: App.activeObject.attr('id'), 
							id: App.userId,
							password:$('#text-box-password-lock').val(), 
							without_pass:App.withoutPass
				});
				App.activateLockedObject(App.activeObject.attr('id'));
			}
			else
			{
				App.passVal = App.lockedObjectList.lockedObject[i].password;
				App.unlockObjectToolbox.show();
			}
		},
		activateLockedObject:function(objectId){
			$('#'+objectId).draggable('enable');
			$('#'+objectId).resizable('enable');
			$('#'+objectId).find("#"+objectId+"-c").attr("disabled", false);
			$('#'+objectId).find("#segrip").attr("disabled", false);
			$('#'+objectId).find("#ngrip").attr("disabled", false);
			$('#'+objectId).find("#sgrip").attr("disabled", false);
			$('#'+objectId).find("#egrip").attr("disabled", false);
			$('#'+objectId).find("#wgrip").attr("disabled", false); 
			$('#'+objectId).css('border','0px dashed #000000');
			// $('#'+objectId).css('z-index','19');
		},
		touchStartCanvas: function(){
			
		},
		
		touchMoveCanvas: function(){
			
		},
		
		touchEndCanvas: function(){
			
		},
		localize : function (string, fallback) {
			var localized = string.toLocaleString();
			if (localized !== string) {
				return localized;
			} else {
				return fallback;
			}
		},
		applyLock:function(lockData)
		{
			//console.log("applyLock");
			for(var i=0;i<lockData.lockedObject.length;i++)
			{
				var lockedObject = lockData.lockedObject[i];
				//console.log(lockedObject);
				if(lockedObject.pageId == App.pageId)
				{
					if(lockedObject.lock_status == App.lockEnum.ALL)
					{
						//console.log($('#'+lockedObject.objectId)); 
						if(App.activeObject)
						{
							if(lockedObject.objectId == App.activeObject.attr('id'))
							{
								var oldActiveWidth = App.activeObject.width();
								var oldActiveHeight = App.activeObject.height();
								
								
								// App.activeObject.css('z-index','18'); 
								$(".resize-grip"+App.activeObject.attr("id")).hide();
								if(App.idIndicatorLast != null || App.idIndicatorLast != 0){
									$(".resize-grip"+App.idIndicatorLast).hide();
									$("#"+App.idIndicatorLast+"-c").hide(); 
								}
								
								App.activeObject.width(oldActiveWidth);
								App.activeObject.height(oldActiveHeight);
								App.activeObject=false;
							}
						}
						$('#'+lockedObject.objectId).draggable('disable');
						$('#'+lockedObject.objectId).resizable('disable');
					}
					else if(lockedObject.lock_status == App.lockEnum.SELECT)
					{
						if(App.activeObject)
						{
							if(lockedObject.objectId == App.activeObject.attr('id'))
							{
								var oldActiveWidth = App.activeObject.width();
								var oldActiveHeight = App.activeObject.height();
								
								if(lockedObject.username != App.username){
									// App.activeObject.css('z-index','18'); 
									$(".resize-grip"+App.activeObject.attr("id")).hide();
									if(App.idIndicatorLast != null || App.idIndicatorLast != 0){
										$(".resize-grip"+App.idIndicatorLast).hide();
										$("#"+App.idIndicatorLast+"-c").hide(); 
									}
								}
								
							}
						}
						$("#"+lockedObject.objectId+"-c").html('');
						$("#"+lockedObject.objectId+"-c").attr('current_user',lockedObject.username);
						
						var fontStr = $('<font></font>').attr({'size':'2', 'face':'comic sans ms'}).appendTo($("#"+lockedObject.objectId+"-c")); 
						if(lockedObject.username.length > 7 ){
							var strCreated =  lockedObject.username.substring(0,7) + "...<br>";
						}else{
							var strCreated =  lockedObject.username + "<br>";
						}
						// if(lockedObject.lockerId.length > 7 ){
							// var strCreated =  lockedObject.lockerId.substring(0,7) + "...<br>";
						// }else{
							// var strCreated =  lockedObject.lockerId + "<br>";
						// }
						fontStr.append(strCreated);
						$("#"+lockedObject.objectId+"-c").show();
						if(lockedObject.username != App.username){
							$('#'+lockedObject.objectId).draggable('disable');
							$('#'+lockedObject.objectId).resizable('disable');
						}
					}
					App.toggleMobileMenuVisibility(lockedObject.objectId,true);
				}
			}
		},
		getLockStatus:function(objectId)
		{
			for(var i=0;i<App.lockedObjectList.lockedObject.length;i++)
			{
				var lockedObject = App.lockedObjectList.lockedObject[i];
				if(lockedObject.objectId == objectId)
				{
					//console.log(lockedObject);
					if(lockedObject.lock_status == App.lockEnum.SELECT && lockedObject.lockerId == App.userId)
						return false;
					else
						return lockedObject.lock_status;
					
				}
			}
			return false;
		},
		getLockerId:function(objectId)
		{
			//console.log(App.lockedObjectList);
			for(var i=0;i<App.lockedObjectList.lockedObject.length;i++)
			{
				var lockedObject = App.lockedObjectList.lockedObject[i];
				if(lockedObject.objectId == objectId)
				{
					return lockedObject.lockerId;
				}
			}
			return false;
		},
		getLockerUsername:function(objectId)
		{
			console.log(App.lockedObjectList);
			for(var i=0;i<App.lockedObjectList.lockedObject.length;i++)
			{
				var lockedObject = App.lockedObjectList.lockedObject[i];
				if(lockedObject.objectId == objectId)
				{
					return lockedObject.username;
					// return lockedObject.lockerId;
				}
			}
			return false;
		},
		toggleMode:function(newMode)
		{	
			if(App.draw.panActive && (App.isModeArea==0 ||  App.isModeArea==2)){//Sedang Pan dan Menuju View Mode
				//Firman : Pan Function : Comment Function and Add New Line
				App.draw.panActive = false;
				App.test = false;
				$(".pan-tools").removeClass('active');
				/*if(navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i)){
					App.draw.endPan();
				}*/
			}
			if(App.openedTool)
			{
				alert(App.localize("%finish_tool"));
				return;
			}
			var nameBrowser = App.setBrowserDetect();
			//alert(nameBrowser);
			if(nameBrowser == "IE")
				$("#overlay").show();
			
			if(newMode == 0 || newMode==2)
				{
					$('#rootContainer').children().each(function(){  
						if($(this).attr('is-template') != 1 && !App.getLockStatus($(this).attr('id')))
						{
							$(this).draggable('disable');
							$(this).resizable('disable');
							$(this).find("#"+$(this).attr('id')+"-c").attr("disabled", true);
							App.toggleMobileMenuVisibility($(this).attr('id'),false);
							$(this).find("#segrip").attr("disabled", true);
							$(this).find("#ngrip").attr("disabled", true);
							$(this).find("#sgrip").attr("disabled", true);
							$(this).find("#egrip").attr("disabled", true);
							$(this).find("#wgrip").attr("disabled", true); 
							$(this).find("#segrip").css("display", "none");
							$(this).find("#ngrip").css("display", "none");
							$(this).find("#sgrip").css("display", "none");
							$(this).find("#egrip").css("display", "none");
							$(this).find("#wgrip").css("display", "none");
						}
					});
					App.isModeArea = 0;
					$('.toggle_mode_buttons').attr('value',App.localize("%edit_mode"));
					if(App.activeObject)
					{
						//release selected object
						var oldActiveWidth = App.activeObject.width();
						var oldActiveHeight = App.activeObject.height();
						App.activeObject.css('border','0px dashed #000000');
						
						if(!App.inBackLayer(App.activeObject))
						App.activeObject.css('z-index','18'); 
						
						$(".resize-grip"+App.activeObject.attr("id")).hide();
						App.toggleMobileMenuVisibility(App.activeObject.attr('id'),false);
						
						App.activeObject.width(oldActiveWidth);
						App.activeObject.height(oldActiveHeight);
						App.socket.emit('cm_deselect_object', {
										roomId: App.fileId, 
										pageId: App.pageId, 
										userId: App.userId,
										username: App.username,
										objectId:App.activeObject.attr('id') 
						});
						App.socket.emit('cm_unlock', {
								roomid: App.fileId,
								pageid:App.pageId,
								status:App.lockEnum.SELECT,
								objectId: App.activeObject.attr('id'), 
								id: App.userId,
								password:"", 
								without_pass:App.withoutPass
							});
						App.activeObject=false;
					}
				}
				else
				{
					$('#rootContainer').children().each(function(){
						if($(this).attr('is-template') != 1  && !App.getLockStatus($(this).attr('id')))
						{
							if(App.getLockStatus($(this).attr("id")) != App.lockEnum.MOVEMENT)
							$(this).draggable('enable');
							$(this).resizable('enable');
							$(this).find("#"+$(this).attr('id')+"-c").attr("disabled", false);
							$(this).find("#segrip").attr("disabled", false);
							$(this).find("#ngrip").attr("disabled", false);
							$(this).find("#sgrip").attr("disabled", false);
							$(this).find("#egrip").attr("disabled", false);
							$(this).find("#wgrip").attr("disabled", false);	 
							$(this).bind('click');
						}
					});
					App.isModeArea = 1;
					$('.drawContainer').css({'cursor':'default'});
					App.draw.panActive=false;
					App.test = false;
					$(".pan-tools").removeClass('active');
					$('.toggle_mode_buttons').attr('value',App.localize("%view_mode"));
				}
			if(nameBrowser == "IE")
				setTimeout(function(){$("#overlay").hide();},2000);
			
			
			
		},
		switchActiveObject:function(newObject)
		{
			if(App.activeObject)
			{		
				var oldActiveWidth = App.activeObject.width();
				var oldActiveHeight = App.activeObject.height();
				if(newObject.attr("type") != "buble")
					App.activeObject.css('border','0px dashed #000000');
				if(!App.inBackLayer(App.activeObject))
				App.activeObject.css('z-index','18'); 
				
				$(".resize-grip"+App.activeObject.attr("id")).hide();
				
				App.toggleMobileMenuVisibility(App.activeObject.attr("id"),false);
				if(App.idIndicatorLast != null || App.idIndicatorLast != 0){
					$(".resize-grip"+App.idIndicatorLast).hide();
					App.toggleMobileMenuVisibility(App.idIndicatorLast,false);
					$("#"+App.idIndicatorLast+"-c").hide(); 
				}
				
				App.activeObject.width(oldActiveWidth);
				App.activeObject.height(oldActiveHeight);
				App.socket.emit('cm_deselect_object', {
								roomId: App.fileId, 
								pageId: App.pageId, 
								userId: App.userId,
								username: App.username,
								objectId:App.activeObject.attr('id') 
				});
				App.socket.emit('cm_unlock', {
							roomid: App.fileId,
							pageid:App.pageId,
							status:App.lockEnum.SELECT,
							objectId: App.activeObject.attr('id'), 
							id: App.userId,
							password:"", 
							without_pass:App.withoutPass
						});
			}  
			
			App.socket.emit('cm_lock', {
										roomid: App.fileId,
										pageid:App.pageId, 
										objectId: newObject.attr("id") , 
										id: App.userId,
										status:App.lockEnum.SELECT, 
										userName: App.username, 
										password:"", 
										without_pass:App.withoutPass
								});
				
			$("#"+newObject.attr("id")+"-c").show(); 
			$(".resize-grip"+newObject.attr("id")).show();
			App.toggleMobileMenuVisibility(newObject.attr("id"),true);
			App.idIndicatorLast = newObject.attr("id");
			App.justSelectAnObject=true;
			
			App.activeObject=newObject;
			if(newObject.attr("type") == "text")
				App.activeObject.css('border','1px dashed #000000');
			if(!App.inBackLayer(App.activeObject))	
			App.activeObject.css('z-index','19');
		},
		undo:function(){
			if(App.actionStack.length==0 || App.currentStackIndex <0)
			{
				return;
			}
		
			console.log("UNDO");
			var currentState = App.actionStack[App.currentStackIndex];
			if(currentState.operation == "EDIT")
			{
				App.updateSingleObject(JSON.parse(currentState.previous_content));
			}
			else if(currentState.operation == "DEL")
			{
				var content = JSON.parse(currentState.previous_content);
				// App.recoverSingleObject(currentState.previous_content);
				var url = App.baseUrl+"CommHub/recover_object_undo/";
				var allData = {
								"file_id":App.fileId,
								"history_id": currentState.history_id,
								"page_id":App.pageId,
								};
				var request =$.ajax({
					type: 'GET',
					url: url,
					data:allData
				});
				request.done(function(msg) {
					App.recoverSingleObject(currentState.previous_content);
				});
			}
			else if(currentState.operation == "ADD")
			{
				var content = JSON.parse(currentState.changed_content);
				var url = App.baseUrl+"CommHub/delete_object/";
				var allData = {
								"file_id":App.fileId,
								"id": content.id,
								"page_id":App.pageId,
								};
				var request =$.ajax({
					type: 'POST',
					url: url,
					data:allData
				});
				request.done(function(msg) {
					$("#"+content.id).remove();
					App.socket.emit('cm_delete', {roomid: App.fileId, deletedId:  content.id, id: App.userId,type:"object" }); 
				});
			}
			App.currentStackIndex--;
			//alert("undo stack len "+App.actionStack.length+ " current index "+App.currentStackIndex);
			
		},
		redo:function(){
		
			if(App.actionStack.length==0)
			{
				
				// alert("can't redo");
				return;
			}
			if(App.actionStack.length == App.currentStackIndex+1)
			{			
			
				// alert("can't redo");
				return;	
			}
			if(App.actionStack.length == App.currentStackIndex-1)
			{
			
				// alert("can't redo");
				return;
			}
			console.log("REDO");
			App.currentStackIndex++;
			var currentState = App.actionStack[App.currentStackIndex];
			console.log(App.actionStack);
			// console.log(App.currentStackIndex);
			console.log(currentState);
			if(currentState.operation == "EDIT")
			{
				App.updateSingleObject(JSON.parse(currentState.changed_content));
			}
			else if(currentState.operation == "DEL")
			{
				var content = JSON.parse(currentState.previous_content);
				// App.recoverSingleObject(currentState.previous_content);
				var url = App.baseUrl+"CommHub/delete_object/";
				var allData = {
								"file_id":App.fileId,
								"id": content.id,
								"page_id":App.pageId,
								};
				var request =$.ajax({
					type: 'POST',
					url: url,
					data:allData
				});
				request.done(function(msg) {
					$("#"+content.id).remove();
					App.socket.emit('cm_delete', {roomid: App.fileId, deletedId:  content.id, id: App.userId,type:"object" }); 
				});
			}
			else if(currentState.operation == "ADD")
			{
				var content = JSON.parse(currentState.changed_content);
				// App.recoverSingleObject(currentState.previous_content);
				var url = App.baseUrl+"CommHub/recover_object_redo/";
				var allData = {
								"file_id":App.fileId,
								"history_id": currentState.history_id,
								"page_id":App.pageId,
								};
				var request =$.ajax({
					type: 'GET',
					url: url,
					data:allData
				});
				request.done(function(msg) {
					App.recoverSingleObject(currentState.changed_content);
				});
			}
			//alert("redo stack len "+App.actionStack.length+ " current index "+App.currentStackIndex);
		},
		updateSingleObject:function(content)
		{
			var existingObject= $("#"+content.id);
	
			console.log("updateing");
			console.log(content);
			if(existingObject)
			{
				 
				var existingType=existingObject.attr('object_type');
				var objectJson = {
						id: content.id, 
						type: existingType, 
				};
				//update content
				var newContent = false;
				if(existingType == "text" || existingType == "buble" || existingType == "sticky-text")
				{
					objectJson.content=content.content;
					if($("#text_content_"+content.id).html() != content.content)
					{
						$("#text_content_"+content.id).html(content.content);
					}
					// if(existingType == "sticky-text")
					// {
						// objectJson.background=content.background;
						// if(existingObject.css('background-color') != content.background)
						// {
							// existingObject.css('background-color', content.background);
							
						// }
					// }
				}
				else if(existingType == "image")
				{
					objectJson.content=content.image_url;
					if($("#img"+content.id).attr('src') != content.image_url)
					{	
						$("#img"+content.id).attr('src',App.baseUrl+content.image_url);
					}
				}
				else if(existingType == "table")
				{
					objectJson.content=content.content_table;
					if($("#tbl_"+content.id).html() != content.content_table)
					{
						$("#tbl_"+content.id).html(content.content_table);
					}
				}
				else if(existingType == "chart")
				{
					var chartObj = $("#"+content.id);
					if(chartObj)
					{
						chartObj.attr('type',content.type)
						.attr('object_type',content.object_type)
						.attr('chart-data',content.data_chart)
						.attr('type_chart',content.type_chart)
						.attr('color1',content.color1)
						.attr('color2',content.color2)
						.attr('color3',content.color3);
						 $("#img"+content.id).attr('src',App.baseUrl+content.image_url);
						 
						objectJson.content={
							type:content.type,
							object_type:content.object_type,
							type_chart:content.type_chart,
							data_chart:content.data_chart,
							color1:content.color1,
							color2:content.color2,
							color3:content.color3,
							image_url:content.image_url,
						};
					}
				}
				
				
				if(content.posx != -1 && content.posy != -1 )
				{
					existingObject.css('left',parseInt(content.posx)+"px");
					existingObject.css('top',parseInt(content.posy)+"px");
				}
				
				if(content.width != -1&& content.height != -1 )
				{
					existingObject.css('width',parseInt(content.width)+"px");
					existingObject.css('height',parseInt(content.height)+"px");
				}
				objectJson.posy = existingObject.position().top;
				objectJson.posx = existingObject.position().left;
				objectJson.width = existingObject.width();
				objectJson.height = existingObject.height();
													
				
				var url = App.baseUrl+"CommHub/update_object_property";
				var newData = {
								"file_id": App.fileId,
								"page_id":App.pageId,
								"object_json":JSON.stringify(objectJson),
							  };
						
				var req = $.ajax({
					type: 'POST',
					url: url,
					data:newData
				});
				req.done(function(msg){
					objectJson.roomid = App.fileId;
					App.socket.emit('cm_update_single_object', objectJson);
				});
			}
			
		},
		toolboxValidation:function(icon_id){
				if(App.isModeArea != 1){
					alert(App.localize("%view_mode_warning_dialog"));
					return false;
				}
				if(App.openedTool)
				{
					if(App.openedTool.attr('id') != icon_id)
					{
						alert(App.localize("%finish_tool"));
					}
					else
					{
						
						alert(App.localize("%tool_open_already"));
					}
					return false;
				}
				return true;
		},
		
		
		toggleMobileMenuVisibility : function(id,visible){
			if($("#context_ico_"+id).attr("enabled") == "1")
			{
				if(visible)
					$("#context_ico_"+id).show();
				else
					$("#context_ico_"+id).hide();
			}
		},
		recoverSingleObject:function(obj){
			console.log(obj);
			msg = JSON.parse(obj);
			console.log(msg);
			if(msg.object_type=="image" || msg.object_type=="shape" || msg.object_type=="stamp")
			{
				App.loadDrawingObject(msg);
				App.socket.emit('cm_new', {roomid: App.fileId,pageid:App.pageId, object:msg, id: App.userId,type:"image" }); 
			}
			else if(msg.object_type=="text")
			{
				App.loadTextObject(msg);
				App.socket.emit('cm_new', {roomid: App.fileId,pageid:App.pageId,  object:msg, id: App.userId,type:"text" }); 
			}
			else if(msg.object_type=="buble")
			{
				App.loadTextObject(msg);
				App.socket.emit('cm_new', {roomid: App.fileId,pageid:App.pageId,  object:msg, id: App.userId,type:"text" }); 
			}
			else if(msg.object_type=="sticky-text")
			{
				// App.loadStickyTextObject(msg);
				App.loadTextObject(msg);
				App.socket.emit('cm_new', {roomid: App.fileId, pageid:App.pageId, object:msg, id: App.userId,type:"sticky-text" }); 
			}
			else if(msg.object_type=="chart")
			{	
				App.loadChartObject(msg);
				App.socket.emit('cm_new', {roomid: App.fileId, pageid:App.pageId, object:msg, id: App.userId,type:"chart" }); 
			}
			else if(msg.object_type=="attach")
			{	
				App.loadDrawingObject(msg);
				App.socket.emit('cm_new', {roomid: App.fileId, pageid:App.pageId, object:msg, id: App.userId,type:"attach" }); 
			}
			else if(msg.object_type=="table")
			{	 
				App.loadTableObject(msg);
				App.socket.emit('cm_new', {roomid: App.fileId,pageid:App.pageId,  object:msg, id: App.userId,type:"table" }); 
			}
		
		},
		setBrowserDetect:function(){
			if(navigator.userAgent.match(/Android/i)
					|| navigator.userAgent.match(/webOS/i)
					|| navigator.userAgent.match(/iPhone/i)
					|| navigator.userAgent.match(/iPad/i)
					|| navigator.userAgent.match(/iPod/i)
					|| navigator.userAgent.match(/BlackBerry/i)
					|| navigator.userAgent.match(/Touch/i)
					|| navigator.userAgent.match(/Windows Phone/i)){						// If device is mobile
					
				return "mobile";
			}else if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ // MSIE x.x; 
				return "IE";
			}
			else if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){ // Firefox/x.x or Firefox x.x (ignoring remaining digits); 
				return "FireFox";
			}
			else if (/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent)){ // Opera/x.x or Opera x.x (ignoring remaining decimal places); 
				return "Opera";
			}
			else if (/Chrome[\/\s](\d+\.\d+)/.test(navigator.userAgent)){ //  Chrome/x.x or Chrome x.x (ignoring remaining decimal places); 
				return "Chrome";
			} 
			else if (/Safari[\/\s](\d+\.\d+)/.test(navigator.userAgent)){ //  Safari/x.x or Safari x.x (ignoring remaining decimal places); 
				return "Safari";
			}
		},
		getAbsoluteCenter:function()
		{
			var wWidth = window.innerWidth;
			var cWidth = $("#rootContainer").width();
			var horizontalCenter = 0;
			var verticalCenter = 0;
			if(wWidth-130 > cWidth)
			{
				  horizontalCenter = Math.floor($("#rootContainer").width()/2);
				  verticalCenter = Math.floor($("#rootContainer").height()/2);
			}
			else
			{
				  horizontalCenter = Math.floor(window.innerWidth/2);
				  verticalCenter = Math.floor(window.innerHeight/2);
				  verticalCenter -= $("#rootContainer").offset().top;
				  horizontalCenter -= $("#rootContainer").offset().left;
			}
			return {x:horizontalCenter,y:verticalCenter};
			//return {x:horizontalCenter + App.draw.panOffset.left,y:verticalCenter + App.draw.panOffset.top};
		},
		updateFileTitle:function()
		{
			$('.file_title').text(App.username+" - "+App.groupname+" - "+App.filename+' '+App.pageId+'/'+App.pageCount);
			$('.file_title').attr('title',App.username+" - "+App.filename+' '+App.pageId+'/'+App.pageCount);
		}
	}
});